简体   繁体   中英

Remove a round transparent section of an Image c#

I am creating an Circle on a bitmap but want to have a hole in it. After serching for half an hour I only found ways to crop an image to a circle. The hard thing is, that the hole in the middle should be transparent as the rest of the Image.

This is the base image and the yellow circle represents the transparent area that should be added.

Thanks for any kind of help.

The start is simple: Create a transparent bitmap by doing a g.Clear(Color.Transparent) and then draw/fill a circle in a color.

The next step is a bit trickier: You next want to paint the hole with transparency.

To do so you need to switch the Graphics object to the right CompositingMode ; default is SourceOver but you want SourceCopy . The former overlays the alpha values creating mixed colors. The latter will do what we want: Draw the hole by copying the drawn colors including alpha right over the old ones..

Here is an example:

Bitmap bmp = new Bitmap(500, 500);
using (Graphics g = Graphics.FromImage(bmp))
{
    g.Clear(Color.Transparent);
    //g.SmoothingMode = SmoothingMode.AntiAlias;
    g.CompositingMode = CompositingMode.SourceCopy;
    g.FillEllipse(Brushes.DarkGreen, 100, 100, 300, 300);
    g.FillEllipse(Brushes.Transparent, 200, 200, 100, 100);
}
pictureBox1.Image = bmp;

This is what is looks like in a PictureBox with a BackgroundImage :

在此处输入图片说明

A few notes:

  • You can also use a semi-transparent brush to create a 'tinted' hole; do not use anti-aliasing for this though, as it would introduce colored fringes.

  • We used simple circles here but with a GraphicsPath you can create and fill shapes of almost any shape and complexity..

  • And using a GraphicsPath would also have been an alternative to filling with transparency: By first adding the large and then the smaller, inner ellipse the path would have been created with a hole and filling it would have had the very same result! But I found the solution above more instructive..

  • Final note: As clarkitect noted, to save, do use a format that supports transparency. Png is always recommended..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM