删除Image c#的圆形透明部分 [英] Remove a round transparent section of an Image c#

查看:170
本文介绍了删除Image c#的圆形透明部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在位图上创建一个Circle,但要在其中留一个孔.进行了半个小时的搜索后,我只找到了将图像裁剪为圆形的方法.困难的是,中间的孔应该与图像的其余部分一样透明.

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.

感谢任何帮助.

推荐答案

开始很简单:通过执行g.Clear(Color.Transparent)创建透明的位图,然后绘制/填充颜色的圆圈.

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.

为此,您需要将Graphics对象切换到右侧的CompositingMode;默认值为SourceOver,但您要SourceCopy.前一个叠加的alpha值可创建混合颜色.后者将满足我们的要求:通过复制绘制的颜色包括alpha 到旧颜色上来绘制孔.

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..

这里是一个例子:

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;

这是带有BackgroundImagePictureBox中的样子:

一些注意事项:

  • 您还可以使用半透明笔刷创建一个有色"孔;不过,请勿为此使用抗锯齿功能,因为这样会引入彩色条纹.

  • 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.

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

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! But I found the solution above more instructive..

最后的注释:如clarkitect所述,为保存起见,请使用支持透明性的格式.始终建议使用Png.

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

这篇关于删除Image c#的圆形透明部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆