Search code examples
c#graphicsgdi+gdiantialiasing

Anti-Aliasing for Regions in C# and Alpha Masking


I want to draw a torus onto a given picture. The torus/ring itself should be drawn with transparency. Because there is no drawTorus, I use graphics path to get the result.

That's my code so far:

Image bmp = Bitmap.FromFile(Application.StartupPath + "\\background.jpg");
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;

Rectangle r1 = new Rectangle(bmp.Width / 2 - bmp.Height / 2, 0, bmp.Height, bmp.Height);
Rectangle r2 = Rectangle.Inflate(r1, -50, -50);

GraphicsPath p1 = new GraphicsPath();
p1.AddEllipse(r1);
GraphicsPath p2 = new GraphicsPath();
p1.AddEllipse(r2);

Region re = new Region(p1);
re.Xor(p2);

g.FillRegion(new SolidBrush(Color.FromArgb(80,0,0,0)),re);
g.Save();

The result looks like this: Result image

The problem with this is, that SmoothingMode is ignored. You can see it here: enter image description here

I've read that this is because Regions aren't affected by the SmoothingMode parameter.

But how to fix it?

  1. Is there an other way to write the code above without regions?
  2. I read about AlphaMasking over here , but this also won't work, because it would influence the transparency of the torus, too.

Solution

  • Use FillPath and your problem should be solved.

    GraphicsPath path = new GraphicsPath();
    path.AddEllipse(r1);
    path.AddEllipse(r2);
    
    using(Brush b = new SolidBrush(Color.FromArgb(80,0,0,0)))
        g.FillPath(b, path);