My Problem with Font Size Setting and Solution Given by Other
Recently, I was developing an application to display information. However, I was troubled by the font size setting.
I created font by following code:
Dim[ myfont AsNew Font(["Arial", size, System.Drawing.FontStyle.Regular)
The problem is that myfont can't recognize it when I set my size value to a lower value. I think over but can't find the solution. Therefore, I ask question on forum to hope that someone can help me.
It is fortunate that one gives me some suggestion. First time, he told me that I can’t change font's properties once it is instantiated for font class is immutable in .Net. And I must dispose it manually to ensure garbage collection as soon as possible. It means that I have to create a new instance and then dispose it when I need a font with a different size.
Then, he gave me the following code:
Using font As New Font("Tahoma", 1.0F, FontStyle.Regular)
'do something with font
End Using 'this will dispose the font
However, I just want to know what is wrong with my code
g.DrawString(scheduleResults(Screen).Item(2).ToString, font1, Brushes.Red, Me.Width * 0.7F, y) or if I should put which font in.
It seems that my code is hard to read in this way. Therefore, he showed me the code and said that I must call g.MeasureString several times for different font sizes if I want to resize a font to fit my form until the text fits the control.
The following is his code:
Dim fontSize As Single = 12.0F
Dim measuredWidth As Single
Do
Using font As New Font("Tahoma", fontSize, FontStyle.Regular)
measuredWidth = g.MeasureString("text", font).Width
End Using
If (measuredWidth > Me.Width) Then
fontSize = fontSize - 0.1
End If
Loop While (measuredWidth > Me.Width)
Using font As New Font("Tahoma", fontSize, FontStyle.Regular)
'do something
End Using
I am very thankful for his help and I solve my problem.
I think that some people may come across the problem with setting font size with VB.NET as me so that I share it and hope the solution to be helpful!