简体   繁体   English

删除Image c#的圆形透明部分

[英]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. 我在位图上创建了一个Circle,但想要在其中有一个孔。 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. 开始很简单:通过执行g.Clear(Color.Transparent)创建透明的位图,然后绘制/填充颜色的圆圈。

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 ; 为此,您需要将Graphics对象切换到正确的CompositingMode default is SourceOver but you want SourceCopy . 默认为SourceOver但您需要SourceCopy The former overlays the alpha values creating mixed colors. 前者覆盖 Alpha值以创建混合颜色。 The latter will do what we want: Draw the hole by copying the drawn colors including alpha right over the old ones.. 后者将执行我们想要的操作:通过绘制的颜色( 包括alpha) 复制到旧颜色上来绘制孔。

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 : 这是带有BackgroundImagePictureBox外观:

在此处输入图片说明

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.. 我们在这里使用了简单的圆形,但是通过GraphicsPath您可以创建和填充几乎任何形状和复杂性的形状。

  • 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! 而且使用GraphicsPath可以替代透明性:通过添加较大的, 然后较小的内部椭圆,将在路径上创建一个孔,并对其进行填充将具有相同的结果! But I found the solution above more instructive.. 但是我发现上面的解决方案更具启发性。

  • Final note: As clarkitect noted, to save, do use a format that supports transparency. 最后说明:如clarkitect所述,要保存,请使用支持透明性的格式。 Png is always recommended.. 始终建议使用Png

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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