2010-04-13 118 views

回答

3
class AutoFontLabel : Label 
{ 
    public AutoFontLabel() 
     : base() 
    { 
     this.AutoEllipsis = true; 
    } 

    protected override void OnPaddingChanged(EventArgs e) 
    { 
     UpdateFontSize(); 
     base.OnPaddingChanged(e); 
    } 

    protected override void OnResize(EventArgs e) 
    { 
     UpdateFontSize(); 
     base.OnResize(e); 
    } 

    private void UpdateFontSize() 
    { 
     int textHeight = this.ClientRectangle.Height 
      - this.Padding.Top - this.Padding.Bottom; 

     if (textHeight > 0) 
     { 
      this.Font = new Font(this.Font.FontFamily, 
       textHeight, GraphicsUnit.Pixel); 
     } 
    } 
} 

感谢AMissico更新控件来处理填充。我们可以看到在设计器中如何改变Padding和TextAlign。

+0

为什么与1f的额外乘法?演员阵容不会更快更清洁吗? (没关系) – AMissico 2010-04-13 11:13:18

+0

这是否会导致额外的标签大小调整,因为您正在更改OnResize中的字体? – AMissico 2010-04-13 11:14:11

+0

不,我试过了,不会导致额外的标签重新显示;基地OnResieze后设置。 – serhio 2010-04-13 11:30:29

0

我认为你需要重写paint方法来解决这个问题,并在你自己的文本上绘制。但是您必须使用GDI +的MeasureString方法来获取文本的大小,因此能够告诉您正确字体大小的例程将以试错方式工作。

+0

我认为宁可用label.OnResize + label.Font =东西的一个伎俩 – serhio 2010-04-13 10:28:42