L. Guthardt
L. Guthardt

Reputation: 2056

Odd behaviour of Graphics.SmoothingMode

I created a Bitmap and draw a simple string and Rectangle on it. Furthermore I set graphics's SmoothingMode to AntiAlias.

orgBitmap = new Bitmap(250, 250);

using (Graphics graphics = Graphics.FromImage(orgBitmap))
{
    graphics.SmoothingMode = SmoothingMode.AntiAlias;

    Rectangle rect = new Rectangle(30, 30, 150, 200);
    graphics.FillRectangle(Brushes.Red, rect);

    using (Pen pen = new Pen(Color.Green, 5))
    {
        graphics.DrawRectangle(pen, rect);
    }

    graphics.DrawString("Test Test Test Test", new Font("Arial", 20, FontStyle.Regular), Brushes.Black, 35, 35);
}

This shows some unexpected behaviour, because not all the graphics have been antialiased. Somehow the antialiasing is limited to all the graphics located in the Rectangles's area. The string drawn outside this area did not get antialiased and I wonder why. Is this a bug or how can I fix it?

enter image description here

Upvotes: 2

Views: 1523

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109567

This is happening because you are drawing the text over an area that has not been initialised - so there's no background colour with which to antialias - it's treating it as transparent (although the background does come out as white, as you can see).

You can easily fix this by calling graphics.Clear(Color.White); immediately before doing the rest of the drawing.

Then it will come out anti-aliased, like so:

enter image description here

Upvotes: 5

Related Questions