How can I make label text scale-able in Winforms application
Asked Answered
B

2

6

I am looking for a way to make text in a label scale-able to it fit in entire parent container. The one way I can think of is to get the container size on window re-size and then increase or decrease font size accordingly, but that would limit its possibilities.

Wondering if there is a better way of doing this, that may work more like an anchor property in Winforms application.

Bear answered 12/12, 2012 at 15:24 Comment(0)
B
4

I knew the answer is hidden somewhere in graphic object and paint event, playing around with these 2 keywords solved my problem. Here is the solution that worked in my particular case.

I am simply changing the font size on paint event for my label as follows:

private void myLabel_Paint(object sender, PaintEventArgs e)
{
     float fontSize = NewFontSize(e.Graphics, parentContainer.Bounds.Size, myLabel.Font, myLabel.Text);
     Font f = new Font("Arial", fontSize, FontStyle.Bold);
     myLabel.Font = f;
}

Where as the NewFontSize function looks like this:

public static float NewFontSize(Graphics graphics, Size size, Font font, string str)
{
    SizeF stringSize = graphics.MeasureString(str, font);
    float wRatio = size.Width / stringSize.Width;
    float hRatio = size.Height / stringSize.Height;
    float ratio = Math.Min(hRatio, wRatio);
    return font.Size * ratio;
}

I also found this article helpful http://www.switchonthecode.com/tutorials/csharp-tutorial-font-scaling

Bear answered 13/12, 2012 at 2:57 Comment(1)
@Xarialon Im 99% sure that the parentContainer is a System.Windows.Forms ControlWeiss
G
1

This expands a little on the accepted answer and works for me:

First I determined my "golden ratio" by setting up a normal Label in the Designer with a Font size that looks nice with the Label.Height property set to 100. This is where I got the Font emSize of 48.0F.

Then in the OnPaint override, if the ratio of 100.0/48.0 changes then just that one time adjust the font and save the new ratio (that way we don't have to make a new font every time the control draws).

It works great to just put it in your Toolbox when you're done alongside the regular Label.

public partial class LabelWithFontScaling : Label
{
    public LabelWithFontScaling()
    {
        InitializeComponent();
    }
    private void InitializeComponent()
    {
        this.SuspendLayout();
        this.Name = "label1";
        this.Size = new System.Drawing.Size(250, 100);
        this.ResumeLayout(false);
    }
    float mRatio = 1.0F;
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        float ratio = e.ClipRectangle.Height / 100.0F;
        if ((ratio > 0.1) && (ratio != mRatio))
        {
            mRatio = ratio;
            base.Font = new Font(Font.FontFamily, 48.0F * ratio, Font.Style);
        }
    }
Gigantes answered 14/8, 2018 at 20:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.