Fix rectangle SmoothingMode problems in C#

[SmoothingMode]

This example explains how to fix a rather obscure SmoothingMode problem.

If you look closely at the PictureBox on the right in the picture, you’ll see that its top and leftmost pixels are not the same color as the rest of the control. The same thing was happening in a program I recently wrote and it took me quite a while to figure out.

This example uses the following code to display colored bitmaps on its two PictureBox controls. The difference between the pieces of code that create the bitmaps for the two controls solves “The Mystery of the Pink Pixels.”

private void Form1_Load(object sender, EventArgs e)
{
    int width, height;
    Bitmap bm;

    width = pictureBox1.ClientSize.Width;
    height = pictureBox1.ClientSize.Height;
    bm = new Bitmap(width, height);
    using (Graphics gr = Graphics.FromImage(bm))
    {
        gr.Clear(Color.Red);
        gr.FillRectangle(Brushes.White, 0, 0, width, height);
    }
    pictureBox1.Image = bm;

    width = pictureBox2.ClientSize.Width;
    height = pictureBox2.ClientSize.Height;
    bm = new Bitmap(width, height);
    using (Graphics gr = Graphics.FromImage(bm))
    {
        gr.SmoothingMode = SmoothingMode.AntiAlias;
        gr.Clear(Color.Red);
        gr.FillRectangle(Brushes.White, 0, 0, width, height);
    }
    pictureBox2.Image = bm;
}

The program gets the first PictureBox control’s client width and height and creates a Bitmap to fit it. It clears the Bitmap with red and then fills the control with a white rectangle that covers the Bitmap. When it has finished, the program displays the Bitmap in the first PictureBox.

Next, the program repeats those steps to make a Bitmap and display it in the second PictureBox. The only difference is that this time it sets the Graphics object’s SmoothingMode property to AntiAlias. That makes drawn shapes such as ellipses and lines look smoother. Unfortunately it also makes the FillRectangle method try to blend its edges into the background colors. Even though the rectangle goes all the way to the edge of the Bitmap, the FillRectangle method tries to blend its edge and that makes it pink instead of white. (It’s a bit odd that FillRectangle doesn’t do the same thing to the bottom and right edges of the rectangle.)

The moral of the story is: if you’re filling a rectangle and you don’t want its edges fuzzy, set SmoothingMode to None before you draw it.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in drawing, graphics and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *