2017-08-08 37 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); 
     } 
    } 
} 
相关问题