Making a font bigger
Despite the age of the .NET framework library, there’s still no straight forward way to make a font bigger. You can’t modify the Size property of a font, instead you have to create a new font and specify the new size and font styles etc. I was tired of writing New Font(…, …, …, … ) all the time, so I decided to add a couple of extensions methods:
Module DrawingExtensions
<Extension()> _
Function GetNewSizedFont(ByVal fnt As Font, ByVal multiplier As Single) As Font
Return New Font(fnt.Name, fnt.Size * multiplier, _
fnt.Style, fnt.Unit)
End Function
<Extension()> _
Function GetNewStyledFont(ByVal fnt As Font, ByVal toggleStyle As FontStyle) As Font
Return New Font(fnt.Name, fnt.Size, _
fnt.Style Xor toggleStyle, fnt.Unit)
End Function
End Module
This is a little better and now lets you write code such as :
Me.Font = Me.Font.GetNewSizedFont(1.25)
Those extensions would work with C# and VB. But with VB there’s more !! In VB you can use properties ByRef and the compiler does the magic for you. (see Jared’s post) So we can change the extensions to Sub’s and make the Font ByRef :
<Extension()> _
Sub ShrinkOrGrow(ByRef fnt As Font, ByVal multiplier As Single)
fnt = New System.Drawing.Font(fnt.Name, fnt.Size * multiplier, _
fnt.Style, fnt.Unit)
End Sub
<Extension()> _
Sub ToggleStyle(ByRef fnt As Font, ByVal toggleStyle As FontStyle)
fnt = New System.Drawing.Font(fnt.Name, fnt.Size, _
fnt.Style Xor toggleStyle, fnt.Unit)
End Sub
Now you can call the extensions on the font property without needing to explicitly re-assign:
Me.Font.ShrinkOrGrow(1.25)
Compare writing :
Me.Font.ToggleStyle(FontStyle.Bold)
To:
Me.Font = New System.Drawing.Font(Me.Font.Name, Me.Font.Size, _
Me.Font.Style Xor FontStyle.Bold, Me.Font.Unit)
Gotta love extensions and VB’s ByRef magic
There’s something about the ByRef version that makes me feel a bit uneasy – it’s not clear in the calling code that the reference is being changed. For example:
Dim OldFont As Font
OldFont = Me.Font
Me.Font.ShrinkOrGrow(2)
MsgBox(Me.Font Is OldFont) ‘ False!
I think I’d prefer to use it like below, but I guess that’s just personal preference:
Dim OldFont As Font
OldFont = Me.Font
Me.Font = Me.Font.ShrinkOrGrow(2)
MsgBox(Me.Font Is OldFont) ‘ still False, but it’s clearer why