VB.NET:如何在运行时组合字体并将其应用于标签?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1350993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.NET: How to compose and apply a font to a label in runtime?
提问by Camilo Martin
I'm developing a Windows Forms Application in Visual Basic .NET with Visual Studio 2008.
我正在使用 Visual Studio 2008 在 Visual Basic .NET 中开发 Windows 窗体应用程序。
I'm trying to compose fonts (Family name, font size, and the styles) at runtime, based on user preferences, and apply them to labels.
我正在尝试根据用户偏好在运行时编写字体(家族名称、字体大小和样式),并将它们应用于标签。
For the sake of both a simplier user interface, and compatibility between more than one machine requiring to use the same font, I'll NOTuse the InstalledFontCollection, but a set of buttons that will set few selected fonts, that I know to be present in all machines (fonts like Verdana).
为了更简单的用户界面以及需要使用相同字体的多台机器之间的兼容性,我不会使用InstalledFontCollection,而是使用一组按钮来设置我知道存在的少数选定字体在所有机器中(像 Verdana 这样的字体)。
So, I have to make a Public Sub on a Module that will create fonts, but I don't know how to code that. There are also four CheckBoxes that set the styles, Bold, Italic, Underline and Strikeout.
因此,我必须在将创建字体的模块上创建一个 Public Sub,但我不知道如何对其进行编码。还有四个复选框可以设置样式,粗体、斜体、下划线和删除线。
How should I code this? The SomeLabel.Font.Boldproperty is readonly, and there seems to be a problem when converting a string like "Times New Roman" to a FontFamily type. (It just says it could not do it)
我应该如何编码?该SomeLabel.Font.Bold属性是只读的,而且似乎像“宋体”这样的字符串转换为fontFamily类型时是一个问题。(它只是说它做不到)
Like on
喜欢
Dim NewFontFamily As FontFamily = "Times New Roman"
Thanks in advance.
提前致谢。
回答by Philip Fourie
This should resolve your font issue:
这应该可以解决您的字体问题:
Label1.Font = New Drawing.Font("Times New Roman", _
16, _
FontStyle.Bold or FontStyle.Italic)
MSDN documentation on Font property here
A possible implementation for the function that creates this font might look like this:
创建此字体的函数的可能实现可能如下所示:
Public Function CreateFont(ByVal fontName As String, _
ByVal fontSize As Integer, _
ByVal isBold As Boolean, _
ByVal isItalic As Boolean, _
ByVal isStrikeout As Boolean) As Drawing.Font
Dim styles As FontStyle = FontStyle.Regular
If (isBold) Then
styles = styles Or FontStyle.Bold
End If
If (isItalic) Then
styles = styles Or FontStyle.Italic
End If
If (isStrikeout) Then
styles = styles Or FontStyle.Strikeout
End If
Dim newFont As New Drawing.Font(fontName, fontSize, styles)
Return newFont
End Function
Fonts are immutable, that means once they are created they cannot be updated. Therefore all the read-only properties that you have noticed.
字体是不可变的,这意味着一旦创建它们就无法更新。因此,您注意到的所有只读属性。

