Hi,
What code should I write so that the Size of the font in a Label will automatically adjust?? base on the width and height of the label... The font size will change not the the Label..
Printable View
Hi,
What code should I write so that the Size of the font in a Label will automatically adjust?? base on the width and height of the label... The font size will change not the the Label..
You would need to use code similar to this:The second argument to the Font constructor is the point size. You might want to use a more complex method of calculating it that takes Height and Width into account. A bit of trial and error should do the job.VB Code:
Private Sub Label1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Label1.Resize Me.Label1.Font = New Font(Me.Label1.Font.FontFamily, Me.Label1.Height / 2) End Sub
Well this is the ugly mess that I have come up with, its far from optimized but you should get the idea, seems to work ok (ish).
Its a sub that you need to call from both the textchanged and resize events of the label... I have included the events so you can see how to do it.
Ideally you would build this functionality into a new control that is derived from Label.
Enjoy.
VB Code:
Private Sub FitLabelText(ByVal sender As Object) Dim lab As Label = CType(sender, Label) Dim gr As Graphics = lab.CreateGraphics Dim sFont As Font Dim layoutSize As SizeF = New SizeF(lab.Width, Label1.Height) Dim sf As StringFormat = New StringFormat(StringFormatFlags.DirectionVertical) Dim charsFitted As Integer Dim lines As Integer Dim sSize As New SizeF Dim i As Integer For i = 8 To 200 '8 is the minimum font size, 200 is the max sFont = New Font(lab.Font.Name, i, lab.Font.Style) sSize = gr.MeasureString(lab.Text, sFont, layoutSize, sf, charsFitted, lines) If charsFitted < lab.Text.Length Then Exit For Next i lab.Font = New Font(lab.Font.Name, i - 1, lab.Font.Style, GraphicsUnit.Pixel) End Sub Private Sub Label1_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.Resize FitLabelText(sender) End Sub Private Sub Label1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Label1.TextChanged FitLabelText(sender) End Sub
PS, my version tries to fit the entire string into the label area, the text can be very tiny if its a long message and a small label.