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.
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