GDI C#倾斜图像后删除背景

时间:2019-08-04 09:47:44

标签: c# gdi+ gdi

我正在尝试根据输入的正方形图像制作具有透明背景的歪斜图像。

到目前为止,歪斜部分仍在起作用,但是未歪斜图像的背景仍然保留。如何从背景中删除未倾斜的图像并将其替换为透明背景?

到目前为止,我已经尝试使用.Clear(Color.Transparent),但它似乎只能使整个图像清晰或不执行任何操作。

到目前为止的代码:

using System;
using System.Drawing;

class Program
{
    static void Main(string[] args)
    {
        Point[] destinationPoints = {
        new Point (150, 20),
        new Point (40, 50),
        new Point (150, 300)
        };

       Image before = Image.FromFile(System.IO.Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
        "before.png"));
       var gr = Graphics.FromImage(before);
       //drawing an ellipse
       Pen myPen = new Pen(Color.Red);
       gr.DrawEllipse(myPen, new Rectangle(0, 0, 200, 300));
       //applying skewed points
       gr.DrawImage(before, destinationPoints);
       var path = System.IO.Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
        "after.png");
       before.Save(path);
    }
}

before.png

before

after.png

after.png

大致预期的结果

rough desired result

1 个答案:

答案 0 :(得分:0)

  

我尝试使用Graphics.Clear(Color.Transparent),但似乎   清除整个图像

的确;您需要选择以首先要清除的零件,这是所有但您绘制倾斜的零件。.:

using System.Drawing.Drawing2D;
..
GraphicsPath gp = new GraphicsPath();
gp.AddRectangle(new Rectangle(Point.Empty, before.Size)); 
gp.AddPolygon(destinationPoints);

这首先选择了整个图像,然后在倾斜的目标区域上切了一个孔。

(注意:GraphicsPath仅允许您对其包含的图形进行添加;默认绕线模式的规则是:除非它们与已存在的区域重叠,否则将添加区域。一次减去等等。)

现在,您有两个选项可以清除图像的未倾斜部分。

您可以透明填充

gr.CompositingMode = CompositingMode.SourceOver;
gr.FillPath(Brushes.Transparent, gp);

或者您可以清除透明标签:

gr.SetClip(gp);
gr.Clear(Color.Transparent);

这应该适用于您的示例图片。

不幸的是,一旦图像的倾斜部分包含非透明像素,此功能将无法使用。在这里原始像素仍会发光。

因此,这种情况的解决方案非常简单:不要在原始位图上绘制,而是使用所需的背景色创建新的位图,并绘制到新的位图上:

Image after = new Bitmap(before.Width, before.Height);
var gr = Graphics.FromImage(after );
gr.Clear(Color.yourChoice);
// now draw as needed..