【问题标题】:How to make sure a font exists before using it with .NET如何在将字体与 .NET 一起使用之前确保字体存在
【发布时间】:2010-10-06 07:19:22
【问题描述】:

我有一个 VB.NET Windows 窗体项目,它在运行时将文本直接绘制到窗体上。不过,在我用字体绘画之前,我想确保字体和字体大小存在于用户的机器上。如果他们不这样做,我会尝试其他一些类似的字体,最终默认使用 Arial 或其他字体。

在用户计算机上测试和验证字体的最佳方法是什么?

【问题讨论】:

    标签: .net vb.net winforms fonts


    【解决方案1】:

    从题为“如何:枚举已安装字体”的 MSDN 文章中,我找到了以下代码:

    InstalledFontCollection installedFontCollection = new InstalledFontCollection(); // Get the array of FontFamily objects. FontFamily[] fontFamilies = installedFontCollection.Families;

    【讨论】:

      【解决方案2】:

      这是一个解决方案,在 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);
              }
          }
      }
      

      这是 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
      

      【讨论】:

      • 由于 Font 是 IDisposable,所以不用时别忘了调用 Dispose。
      【解决方案3】:

      另请参阅导致此代码的same question

          private bool IsFontInstalled(string fontName) {
              using (var testFont = new Font(fontName, 8)) {
                  return 0 == string.Compare(
                    fontName,
                    testFont.Name,
                    StringComparison.InvariantCultureIgnoreCase);
              }
          }
      

      【讨论】:

        【解决方案4】:

        Arial Bold Italic 不太可能是一种字体。它是 Arial 家族的子类。

        尽量保持简单并测试“Arial”。

        【讨论】:

          猜你喜欢
          • 2014-06-24
          • 1970-01-01
          • 2016-02-08
          • 2013-04-12
          • 1970-01-01
          • 1970-01-01
          • 2013-07-15
          • 1970-01-01
          • 2011-07-06
          相关资源
          最近更新 更多