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
In case you’ve missed it, Lucian Wishick from the VB team is doing a set of blog posts about feature ideas for future versions of VB (VB11 and later). Lucian assures me **ALL** of the ideas in my previous wish list for VB10 are on the list !!!!
Now’s a great time to speak up and discuss these and other features you might have in mind.