Habi
Habi

Reputation: 3300

Anti-Aliased Text in a Transparent .NET Form

I have a C# application which shows the current time in a transparent .NET Form. The Form has no controls and no border. Its property TransparencyKey is set to the Form's background color "light gray" to make it transparent.
So the user can only see the text (current time).

The text is drawn in the PaintEventHandler:

private void Display_Paint( object sender, PaintEventArgs e )
{
    Graphics formGraphics = e.Graphics;

    Font myFont = new Font( "Microsoft Sans Serif", 24, FontStyle.Bold );

    formGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
    //formGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;

    formGraphics.DrawString( "00:00:00", myFont, Brushes.Green, 0.0F, 0.0F );

    myFont.Dispose();
}

Due to the anti-aliasing the text "00:00:00" is shown frayed when the Form is over a dark background. For light backgrounds the text is o.k.

This image shows the problem and the good case:

text shows fringes due to anti-aliasing for dark background
(source: habermann-net.de)

Obviously Windows does render the text in a way that it fits to the Form's own background color and not in a way that it fits to the background which is behind the transparent Form.

Is it possible to let Windows take the background behind the Form into account when rendering the text so that I get rid of the fringes?

One "solution" could be to switch off anti-aliasing by setting TextRenderingHint accordingly. But up to now this is not my preferred "solution".

System:
Windows XP, SP 3, .NET 3.5, VS 2008

Upvotes: 9

Views: 3793

Answers (2)

Jim Schubert
Jim Schubert

Reputation: 20357

In your Display_Paint method, try this:

this.SetStyle(ControlStyles.DoubleBuffer | 
      ControlStyles.UserPaint | 
      ControlStyles.AllPaintingInWmPaint,
      true);
this.UpdateStyles();

Upvotes: -1

iano
iano

Reputation: 2026

I asked a similar question a few months ago.

What I ended up doing was having two options:

  1. Copy the background behind the application by setting its opacity to 0 temporarily, then draw antialiased text onto that. This approach works well if the window and those under it don't move often.
  2. Using a layered window. Works better than TransparencyKey, but still works best with non-antialiased text. (just avoid using a ClearType font and you will be fine)

Upvotes: 2

Related Questions