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



我用了这个答案:前彩中的阿尔法 以创建自定义标签元素,该元素允许在 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 实现到这个类中,从而允许文本内容正确对齐。

多亏了@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);
}
}   
}

最新更新