2017-08-08 75 views
0

我使用此答案:Alpha in ForeColor 創建自定義標籤元素,允許通過ARGB淡入淡出,這與默認標籤不同。自定義winforms標籤控件中的對齊

using System; 
using System.Drawing; 
using System.Windows.Forms; 

public class MyLabel : Label { 
    protected override void OnPaint(PaintEventArgs e) { 
    Rectangle rc = this.ClientRectangle; 
    StringFormat fmt = new StringFormat(StringFormat.GenericTypographic); 
    using (var br = new SolidBrush(this.ForeColor)) { 
     e.Graphics.DrawString(this.Text, this.Font, br, rc, fmt); 
    } 
    } 
} 

我很好奇我將如何在這個類中實現TextAlign,使文本內容能夠正確對齊。

+1

設置'StringFormat'屬性:https://msdn.microsoft.com/en-us/library/system.drawing.stringformat.alignment(v = vs.110).aspx – Aybe

回答

0

感謝@ Aybe的評論,我計算出我需要的線添加到的StringFormat VAR FMT這樣的:

fmt.Alignment = StringAlignment.Center; 

使得整個階級是這樣的:

using System; 
using System.Drawing; 
using System.Windows.Forms; 

public class MyLabel : Label { 
    protected override void OnPaint(PaintEventArgs e) { 
    Rectangle rc = this.ClientRectangle; 
    StringFormat fmt = new StringFormat(StringFormat.GenericTypographic); 
    fmt.Alignment = StringAlignment.Center; 
     using (var br = new SolidBrush(this.ForeColor)) 
     { 
      e.Graphics.DrawString(this.Text, this.Font, br, rc, fmt); 
     } 
    } 
}