【问题标题】:Alignment in custom winforms label control自定义winforms标签控件中的对齐
【发布时间】:2018-01-16 15:50:38
【问题描述】:

我使用了这个答案: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 以使文本内容正确对齐。

【问题讨论】:

标签: c# winforms label text-alignment


【解决方案1】:

感谢@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);
        }
    }   
}

【讨论】:

  • 我建议在某处添加e.Graphics.Clear(this.BackColor);(可能在方法的开头)。如果没有使用您的解决方案,我遇到了一些奇怪的文本显示问题
猜你喜欢
  • 2010-09-10
  • 2010-12-14
  • 1970-01-01
  • 2021-08-08
  • 2018-02-20
  • 2014-11-26
  • 2017-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多