【问题标题】:Font is installed? function字体安装了吗?功能
【发布时间】:2013-03-31 15:31:47
【问题描述】:

我可以改进我的功能以不按每个元素进行搜索?

#Region " Font Is Installed? Function "

    ' [ Font Is Installed? Function ]
    '
    ' Examples :
    ' MsgBox(Font_Is_Installed("Lucida Console"))

    Private Function Font_Is_Installed(ByVal FontName As String) As Boolean
        Dim AllFonts As New Drawing.Text.InstalledFontCollection
        For Each Font As FontFamily In AllFonts.Families
            If Font.Name.ToLower = FontName.ToLower Then Return True
        Next
        Return False
    End Function

#End Region

更新:

好的,现在我看到了“.tolist”函数,现在我的代码是这样的:

Private Function Font_Is_Installed(ByVal FontName As String) As Boolean
    Dim AllFonts As New Drawing.Text.InstalledFontCollection
    Dim FontFamily As New FontFamily(FontName)
    If AllFonts.Families.ToList().Contains(FontFamily) Then Return True Else Return False
End Function

我也有同样的问题:是第二种方式改进最好,还是我可以改进得更好?

【问题讨论】:

    标签: vb.net visual-studio visual-studio-2012 fonts font-family


    【解决方案1】:

    这里是

        Public Shared Function IsFontInstalled(ByVal FontName As String) As Boolean
            Using TestFont As Font = New Font(FontName, 10)
                Return CBool(String.Compare(FontName, TestFont.Name, StringComparison.InvariantCultureIgnoreCase) = 0)
            End Using
        End Function
    

    【讨论】:

    • 谢谢,但我有两个小问题:第一:返回值后最终使用是否有效?我的意思是“TestFont”是否真的在“return”之后结束/关闭?第二:你的方式不比较每个元素? (对不起,如果这是一个愚蠢的问题)
    • 您只想检查是否安装了字体,永远不会有两个同名的字体,结束使用它就可以了,它仍然会从内存中清除对象
    【解决方案2】:
        Dim SomeTextBox As TextBox = New TextBox()
        Dim SomeFontFamily As FontFamily = Nothing
        Dim SomeFontCollection As PrivateFontCollection = Nothing
    
        Try
            SomeFontFamily = New FontFamily("SomeFontFamilyName")
        Catch ex As Exception
            SomeFontCollection = New PrivateFontCollection()
            SomeFontCollection.AddFontFile("SomeFontFileName")
            SomeFontFamily = SomeFontCollection.Families(0)
        End Try
    
        SomeTextBox.Font = New Font(SomeFontFamily, 12)
    

    这种方式 SomeFontFamily 只有在不能从本地字体创建的情况下才会从文件创建。 SomeTextBox 将显示正确的字体。

    【讨论】:

      【解决方案3】:

      这是一个例子。只需尝试分配一个字体名称,如果它产生错误,抓住它并返回 false。

      Private Function isFontInstalled(ByVal FontName As String) As Boolean
          Try
              Dim FontFamily As New FontFamily(FontName)
              FontFamily.Dispose()
              Return True
          Catch
              Return False
          End Try
      End Function
      

      【讨论】:

        猜你喜欢
        • 2014-12-23
        • 2011-02-15
        • 2010-09-11
        • 1970-01-01
        • 2022-01-11
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        • 2014-01-06
        相关资源
        最近更新 更多