自定义winforms标签控件中的对齐方式

时间:2017-08-08 22:42:33

标签: c# winforms label text-alignment

我用了这个答案:Alpha in ForeColor 创建一个允许淡化ARGB的自定义标签元素,与默认标签不同。

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 个答案:

答案 0 :(得分: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);
        }
    }   
}