【问题标题】:GDI C# Remove Background After Skewing Image倾斜图像后 GDI C# 删除背景
【发布时间】:2019-12-12 04:56:46
【问题描述】:

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

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

到目前为止,我已经尝试过使用.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);
    }
}

之前.png

之后.png

粗略的预期结果

【问题讨论】:

  • 您的问题解决了吗?

标签: c# gdi+ gdi


【解决方案1】:

我尝试过使用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);

或者你也可以clear用透明:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多