Autorun font size

For the parameter, is System.Windows.Forms.Label

there a way to automatically set the label font size based on the label size?

+2


a source to share


2 answers


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 for updating the add-on handling control. We can see how the Padding and TextAlign settings are changed in the designer.

+3


a source


I think you will need to override the draw method to solve this problem and draw your own text. But you will need to use the MeasureString method for GDI + to get the text size, so the procedure that tells you the correct font size will work through trial and error.



0


a source







All Articles