AutoFit标签字体大小

时间:2010-04-13 10:20:36

标签: .net winforms font-size

对于System.Windows.Forms.Label,有没有办法根据标签尺寸自动调整标签字体大小?

2 个答案:

答案 0 :(得分:3)

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);
        }
    }
}

感谢AMissico更新控件以处理填充。我们可以看到如何在设计器中更改Padding和TextAlign。

答案 1 :(得分:0)

我认为你需要覆盖paint方法来解决这个问题,并在你自己的文本上绘画。但是你必须使用GDI +的MeasureString方法来获取文本的大小,所以告诉你正确字体大小的例程将以反复试验的方式工作。