Leo Vo
Leo Vo

Reputation: 10330

Alpha in ForeColor

I want to create a fading effect of text in Label control. I change Alpha value in Label's ForeColor but it is not affected.

I see a same question at here: http://phorums.com.au/showthread.php?190812-Alpha-value-of-the-forecolor-of-vs-2005-controls but no answer.

Please help me. Thanks.

Upvotes: 4

Views: 1837

Answers (1)

Hans Passant
Hans Passant

Reputation: 941475

The TextRenderer class uses GDI's DrawTextEx() function, it doesn't support transparency. Setting UseCompatibleTextRendering to true doesn't help either, the Label class forces the foreground color to an alpha of 255 to keep it compatible with TextRenderer. All you can do is write your own paint override.

Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form. Beware that I took a few short-cuts, it doesn't implement alignment, padding and Enabled.

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

Upvotes: 4

Related Questions