ForeColor中的Alpha

时间:2010-04-14 08:55:33

标签: c# .net

我想在Label控件中创建文本的淡化效果。我更改了Label的ForeColor中的Alpha值,但它没有受到影响。

我在这里看到同样的问题: http://phorums.com.au/showthread.php?190812-Alpha-value-of-the-forecolor-of-vs-2005-controls 但没有答案。

请帮帮我。感谢。

1 个答案:

答案 0 :(得分:3)

TextRenderer类使用GDI的DrawTextEx()函数,它不支持透明度。将UseCompatibleTextRendering设置为true也无济于事,Label类将前景色强制为255的alpha值,以使其与TextRenderer兼容。您所能做的就是编写自己的油漆覆盖。

在项目中添加一个新类并粘贴下面显示的代码。编译。将新控件从工具箱顶部拖放到表单上。请注意我采取了一些快捷方式,它没有实现对齐,填充和启用。

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);
    }
  }
}