Wie stellen Sie sicher, dass eine Schriftart vorhanden ist, bevor es mit .NET
Frage
Ich habe eine VB.NET Windows-Forms-Projekt, den Text direkt auf das Formular zur Laufzeit in einem Punkt malt. Bevor ich mit der Schrift obwohl malen, möchte ich sicherstellen, dass die Schriftart und Schriftgröße auf dem Computer des Benutzers vorhanden ist. Wenn sie dies nicht tun, werde ich ein paar andere ähnlichen Schriften versuchen, eventuell mit Arial oder etwas in Verzug.
Was ist der beste Weg, eine Schriftart auf dem Computer eines Benutzers zu testen und zu validieren?
Lösung
Von einem MSDN-Artikel mit dem Titel "How To: Aufzählen installierten Schriftarten", fand ich diesen Code ein:
InstalledFontCollection installedFontCollection = new InstalledFontCollection();
// Get the array of FontFamily objects.
FontFamily[] fontFamilies = installedFontCollection.Families;
Andere Tipps
Hier ist eine Lösung, in c #:
public partial class Form1 : Form
{
public Form1()
{
SetFontFinal();
InitializeComponent();
}
/// <summary>
/// This method attempts to set the font in the form to Cambria, which
/// will only work in some scenarios. If Cambria is not available, it will
/// fall back to Times New Roman, so the font is good on almost all systems.
/// </summary>
private void SetFontFinal()
{
string fontName = "Cambria";
Font testFont = new Font(fontName, 16.0f, FontStyle.Regular,
GraphicsUnit.Pixel);
if (testFont.Name == fontName)
{
// The font exists, so use it.
this.Font = testFont;
}
else
{
// The font we tested doesn't exist, so fallback to Times.
this.Font = new Font("Times New Roman", 16.0f,
FontStyle.Regular, GraphicsUnit.Pixel);
}
}
}
Und hier ist eine Methode in VB:
Public Function FontExists(FontName As String) As Boolean
Dim oFont As New StdFont
Dim bAns As Boolean
oFont.Name = FontName
bAns = StrComp(FontName, oFont.Name, vbTextCompare) = 0
FontExists = bAns
End Function
Siehe auch diese gleiche Frage , die in diesem Code-Ergebnisse:
private bool IsFontInstalled(string fontName) {
using (var testFont = new Font(fontName, 8)) {
return 0 == string.Compare(
fontName,
testFont.Name,
StringComparison.InvariantCultureIgnoreCase);
}
}
Arial Bold Italic ist unwahrscheinlich, dass eine Schrift sein. Es ist eine Unterklasse der Arial Familie.
Versuchen Sie es einfach und Test für 'Arial' zu halten.