Determine Label Size Based Upon Amount of Text and Font Size in Winforms/C#

Determine Label Size based upon amount of text and font size in Winforms/C#

How about Graphics.MeasureString, with the overload that accepts a string, the font, and the max width? This returns a SizeF, so you can round round-off the Height.

        using(Graphics g = CreateGraphics()) {
SizeF size = g.MeasureString(text, lbl.Font, 495);
lbl.Height = (int) Math.Ceiling(size.Height);
lbl.Text = text;
}

Determine Label Size based upon amount of text and font size in Winforms/C#

How about Graphics.MeasureString, with the overload that accepts a string, the font, and the max width? This returns a SizeF, so you can round round-off the Height.

        using(Graphics g = CreateGraphics()) {
SizeF size = g.MeasureString(text, lbl.Font, 495);
lbl.Height = (int) Math.Ceiling(size.Height);
lbl.Text = text;
}

font size affecting size of Label

Something like

private void Form1_Resize(object sender, EventArgs e)
{

Font f;
Graphics g;
SizeF s;
Single Faktor, FaktorX, FaktorY;

g = label2.CreateGraphics();
s = g.MeasureString(label2.Text, label2.Font, label2.Size);
g.Dispose();

FaktorX = label2.Width / s.Width;
FaktorY = label2.Height / s.Height;

if (FaktorX > FaktorY)
{
Faktor = FaktorY;
}
else
{
Faktor = FaktorX;
}

f = label2.Font;
label2.Font = new Font(f.Name, f.SizeInPoints * Faktor);
}

It is not pretty but you can work on this

valter

How does the size get calculated when using GetPreferredSize()?

 Size sz = new Size(this.Width, Int32.MaxValue);
sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
this.Height = sz.Height;

where "this " is your control.

Resize text size of a label when the text gets longer than the label size?

You can use my code snippet below. System needs some loops to calculate the label's font based on text size.

while(label1.Width < System.Windows.Forms.TextRenderer.MeasureText(label1.Text, 
new Font(label1.Font.FontFamily, label1.Font.Size, label1.Font.Style)).Width)
{
label1.Font = new Font(label1.Font.FontFamily, label1.Font.Size - 0.5f, label1.Font.Style);
}

auto size of label height and width in C#

One basic strategy is to set the MaximumSize.Width property so the label cannot grow horizontally beyond the window edge or overlap another control. It will now automatically wrap long text, adding lines vertically.

You may well also want to set the MaximumSize.Height property so the height cannot get out of control either. In which case you also want to set the AutoEllipsis property to True. So that the user can tell that the text was clipped and a ToolTip is automatically displayed when he hovers the mouse over the label.



Related Topics



Leave a reply



Submit