Question Auto Resize text on button

Danerd100

Member
Joined
Aug 31, 2008
Messages
8
Programming Experience
1-3
Hi all,
I am writing a program that programmatically generates buttons based on database information. The buttons CANNOT be more than 75,75 in size. The problem is, if the text is longer than 9 characters, it moves the rest on to a second line. How can I make the font size automatically adjust to have larger text if it can, and if not, have smaller text to fit on one line

Thanks in advance
 
Example using MeasureString to figure out how large the text will be based on a beginning font (in this case 8 pt Microsoft Sans Serif) and then adjusting the font size based on how much larger the text is than the writable area.

Ratios > 1 mean the font would need to be scaled up to fill the width and don't need to be scaled.

Magic number of 62 is from a 75px button appearing to have 13px of fluff that you can't write on. Found by simple trial and error.

VB.NET:
		Const theText1 As String = "123"
		Const theText2 As String = "1234567890123"

		Dim theFont As New Font("Microsoft Sans Serif", 8)

		Dim theSize1 As New SizeF
		Dim theSize2 As New SizeF

		Dim b As New Bitmap(1, 1, Imaging.PixelFormat.Format32bppArgb)
		Dim g As Graphics = Graphics.FromImage(b)

		theSize1 = g.MeasureString(theText1, theFont)
		theSize2 = g.MeasureString(theText2, theFont)

		If 62 / theSize1.Width < 1 Then
			Me.Button1.Font = New Font("Microsoft Sans Serif", 62 / theSize1.Width * 8)
		End If
		Me.Button1.Text = theText1

		If 62 / theSize2.Width < 1 Then
			Me.Button2.Font = New Font("Microsoft Sans Serif", 62 / theSize2.Width * 8)
		End If
		Me.Button2.Text = theText2
 
Back
Top