[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Fix rectangle SmoothingMode problems in C#

[Fix rectangle SmoothingMode problems in C#]

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.