C# Anti Aliasing when drawing

In a previous post I talked about how to set anti-aliasing on text in C#. Now you may find yourself needing to set anti aliasing when drawing shapes. This is very easy to do using the GDI+ graphics object. The trick is to use the SmoothingMode and PixelOffsetMode.

Now some quick code

protected override void OnPaint( PaintEventArgs e )
{
     e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
     e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
     e.Graphics.DrawEllipse( new Pen( new SolidBrush( Color.Red ), 1.0f ), new Rectangle( 5, 5, 200, 200 ) );

     e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
     e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
     e.Graphics.DrawEllipse( new Pen( new SolidBrush( Color.Red ), 1.0f ), new Rectangle( 210, 5, 200, 200 ) );

     e.Graphics.SmoothingMode = SmoothingMode.HighSpeed;
     e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
     e.Graphics.DrawEllipse( new Pen( new SolidBrush( Color.Red ), 1.0f ), new Rectangle( 415, 5, 200, 200 ) );

     e.Graphics.SmoothingMode = SmoothingMode.Default;
     e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
     e.Graphics.DrawEllipse( new Pen( new SolidBrush( Color.Red ), 1.0f ), new Rectangle( 620, 5, 200, 200 ) );


     base.OnPaint( e );
}


Now as you can see we start with the higher quality AA setting and move down to the default setting. I kept the PixelOffsetMode to high quality for all tests. You can play around with the different settings to achieve the desired results. We do a lot of image generation and have them both set to as high as possible and don't see a large impact on drawing performance by using AA.

Comments

Popular posts from this blog

String.Replace vs Regex.Replace

C# Form Application in Kiosk Mode/Fullscreen

Javascript numeric only text box