For a System.Windows.Forms.Label
is there a way to auto-fit the label font size depending on the label size?
views:
163answers:
2
A:
I think you would need to override the paint method to solve this, and paint on your own text. But you'll have to use the MeasureString method of GDI+ to get the size of the text, so the routine which will tell you the correct font size will work in a trial-and-error fashion.
Gerrie Schenck
2010-04-13 10:26:34
I thought rather to a trick with label.OnResize + label.Font = something
serhio
2010-04-13 10:28:42
+2
A:
class AutoFontLabel : Label
{
public AutoFontLabel()
: base()
{
this.AutoEllipsis = true;
}
protected override void OnPaddingChanged(EventArgs e)
{
UpdateFontSize();
base.OnPaddingChanged(e);
}
protected override void OnResize(EventArgs e)
{
UpdateFontSize();
base.OnResize(e);
}
private void UpdateFontSize()
{
int textHeight = this.ClientRectangle.Height
- this.Padding.Top - this.Padding.Bottom;
if (textHeight > 0)
{
this.Font = new Font(this.Font.FontFamily,
textHeight, GraphicsUnit.Pixel);
}
}
}
Thanks to AMissico that updated the control to handle padding. We can see how changing the Padding and TextAlign are affectd in the designer.
serhio
2010-04-13 10:58:54
Why the extra multiplication with 1f? Won't a cast be quicker/cleaner? (Not that it matters)
AMissico
2010-04-13 11:13:18
Does this cause an extra label resize because you are changing the font within OnResize?
AMissico
2010-04-13 11:14:11
no, i tried, does not cause an extra label resieze; base OnResieze is set after.
serhio
2010-04-13 11:30:29
+1, I like it. Clever. I would add that you should consider using Padding. This would remove the hard-coding of 1.6f, and you can adjust padding through the designer.
AMissico
2010-04-13 11:33:13
@AMissivo: yes, I can use Padding, but afraid that this will not eliminate the scale ratio: 1.6f
serhio
2010-04-13 11:38:26
have you remarked the top text interspace is larger that the bottom one?!
serhio
2010-04-13 13:19:36
Dock fill should be working. I tested by placing two controls on form, setting dock fill with send to back, running form, and sizing form. The background label sized properly and the foreground label stayed the same because I left anchor and dock to defaults.
AMissico
2010-04-13 14:48:18
Yes, that is because of the TextAlign property. Try different values for this property to see the effects. There is not much difference with top/middle/center. After setting TextAlign, use Padding to adjust to liking.
AMissico
2010-04-13 14:53:02