|
-
Jul 14th, 2005, 05:08 AM
#1
Thread Starter
Hyperactive Member
Label Font(size autosize)
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..
-
Jul 14th, 2005, 06:24 AM
#2
Re: Label Font(size autosize)
You would need to use code similar to this:
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
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.
-
Jul 14th, 2005, 06:37 AM
#3
Re: Label Font(size autosize)
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
I don't live here any more.
-
Jul 14th, 2005, 06:38 AM
#4
Re: Label Font(size autosize)
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.
I don't live here any more.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|