据我所知,更改System.Windows.Forms.Label的字体大小并不会影响(影响?)它的大小。但是,就我而言,似乎确实如此。我在下面的代码示例中想要的是填充屏幕的Label。我通过将它放在TableLayoutPanel中并使两者都具有DockStyle.Fill来实现。我将标签设为红色以提高可视性。
现在我开始乱搞每个调整大小的字体大小。如果我将font-size设置为特定值,则一切都按预期工作。但是,如果我将Font-size设置为动态的,无论多么简单,我都会将Label的大小重置为初始大小(100,23)并保持该大小。为什么会这样?
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;
}
}
当我想动态设置Label的字体大小时,问题就出现了,文本总是尽可能地填充Label的大小。
答案 0 :(得分:0)
像
这样的东西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);
}
它不漂亮,但你可以在这个
上工作瓦尔特