AutoFit Label Font Size

。_饼干妹妹 提交于 2020-01-04 11:03:06

问题


For a System.Windows.Forms.Label is there a way to auto-fit the label font size depending on the label size?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/2628725/autofit-label-font-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!