Reputation: 28586
For a System.Windows.Forms.Label
is there a way to auto-fit the label font size depending on the label size?
Upvotes: 2
Views: 3531
Reputation: 28586
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.
Upvotes: 3
Reputation: 22368
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.
Upvotes: 0