自定义 winforms 标签控件中的对齐
Alignment in custom winforms label control
我使用了这个答案: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);
}
}
}
我很好奇我将如何在此 class 中实现 TextAlign 以允许正确对齐文本内容。
感谢@Aybe 的评论,我发现我需要像这样将 Alignment 添加到 StringFormat var fmt:
fmt.Alignment = StringAlignment.Center;
使整个 class 看起来像这样:
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);
}
}
}
我使用了这个答案: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);
}
}
}
我很好奇我将如何在此 class 中实现 TextAlign 以允许正确对齐文本内容。
感谢@Aybe 的评论,我发现我需要像这样将 Alignment 添加到 StringFormat var fmt:
fmt.Alignment = StringAlignment.Center;
使整个 class 看起来像这样:
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);
}
}
}