VB.NET: How to compose and apply a font to a label in runtime?

梦想的初衷 提交于 2019-12-23 08:59:59

问题


I'm developing a Windows Forms Application in Visual Basic .NET with Visual Studio 2008.

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 NOT use 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).

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.

How should I code this? The SomeLabel.Font.Bold property 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)

Like on

Dim NewFontFamily As FontFamily = "Times New Roman"

Thanks in advance.


回答1:


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.



来源:https://stackoverflow.com/questions/1350993/vb-net-how-to-compose-and-apply-a-font-to-a-label-in-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!