字体大小影响标签大小 [英] font size affecting size of Label
问题描述
据我所知,更改 System.Windows.Forms.Label 的字体大小不会影响(效果?)它的大小.但是,就我而言,它似乎确实如此.在下面的代码示例中,我想要的是一个填充屏幕的标签.我通过将它放在 TableLayoutPanel 中来做到这一点,并使两者都具有 DockStyle.Fill.为了可见性,我将标签设为红色.
As far as I know, changing the Font size of a System.Windows.Forms.Label doesn't affect (effect?) it's size. However, in my case it seems it does. What I want in the following code example is a Label that fills the screen. I do that by placing it in a TableLayoutPanel and make both have DockStyle.Fill. I made the Label red for visibility.
现在我开始在每次调整大小时弄乱字体大小.如果我将字体大小设置为特定值,一切都会按预期进行.但是,如果我将 Font-size 设置为动态的,无论多么简单,我都会将 Label 的大小重置为 (100, 23) 的初始大小并保持该大小.为什么会发生这种情况?
Now I start messing around with the font-size on each resize. If I set the font-size to a specific value, everything works as expected. However if I set the Font-size to something dynamic, however simplistic, I get that the size of the Label resets to the initial size of (100, 23) and stays at that size. Why does this happen?
public class Form2 : Form
{
public Form2()
{
this.DoubleBuffered = true;
//Create a TableLayoutPanel that covers the entire screen with 1 cell.
TableLayoutPanel TLP = new TableLayoutPanel();
TLP.Dock = DockStyle.Fill;
TLP.RowCount = 1;
TLP.RowStyles.Add(new RowStyle(SizeType.Percent, 1F));
TLP.ColumnCount = 1;
TLP.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 1F));
//Create a Label that fills the entire cell of the TableLayoutPanel. Make the Label red to visualise it's size.
Label label1 = new Label();
label1.BackColor = Color.Red;
label1.Dock = DockStyle.Fill;
label1.Resize += new EventHandler((o,e) => Form2.test((Label)o));
TLP.Controls.Add(label1, 0, 0);
//Add the TableLayoutPanel to the controls
this.Controls.Add(TLP);
}
//Methode that messes around with the font-size a bit.
public static void test(Label label1)
{
if (label1.Font.Size == 3)
{
label1.Font = new Font(label1.Font.FontFamily, 4F);
}
else
{
label1.Font = new Font(label1.Font.FontFamily, 3F);
}
return;
}
}
当我想以这样一种方式动态设置标签的字体大小时,出现了这个问题,即文本总是尽可能地填充标签的大小.
This problem came up when I wanted to dynamicly set the font-size of a Label in such a way that the text always filled the size of the Label as good as possible.
推荐答案
类似的东西
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
瓦尔特
这篇关于字体大小影响标签大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!