c# GDI -如何创建多边形(点集)的位图副本

本文关键字:多边形 点集 副本 位图 GDI 何创建 创建 | 更新日期: 2023-09-27 18:04:49

我有一个位图对象(甚至任何其他图像),我在这个位图上画一些线来创建一个多边形。绘图后,我需要克隆/复制/剪切选择(基于线条)区域。

我不能使用位图。克隆方法,因为它只对矩形有效。

我需要某种基于Point[]或GraphicsPath的克隆实现…

请帮助新的GDI/图形…:)

我试着这样做:

Graphics g = pbImage.CreateGraphics();
g.Clip = new Region(path);
Image img = null;
g.DrawImage(img, new Point(0, 0));

你能提供一个代码示例吗?我是GDI+的新手,我不能实现你的建议。

我不明白:

另一个缓冲区/临时图形对象

c# GDI -如何创建多边形(点集)的位图副本

Barndon Moretzs解的一个例子。

        int x = 0;
        int y = 0;
        int width = 0;
        int height = 0;
        Point[] pesource = null;
        GraphicsPath gpdest = new GraphicsPath();
        source = new Bitmap(Image.FromFile(@"IMAGEPATH"));
        //Your polygon
        pesource = new Point[]
        {
            new Point(10,100),
            new Point(30,150),
            new Point(40,170),
            new Point(60,120),
            new Point(70,250),
            new Point(40,300),
            new Point(10,250),
            new Point(30,150)
        };
        //Determine the destination size/position
        x = source.Width;
        y = source.Height;
        foreach (var p in pesource)
        {
            if (p.X < x)
                x = p.X;
            if (p.X > width)
                width = p.X;
            if (p.Y < y)
                y = p.Y;
            if (p.Y > height)
                height = p.Y;
        }
        height = height - y;
        width = width - x;

        gpdest.AddPolygon(pesource);
        Matrix m = new Matrix(1, 0, 0, 1, -x, -y);
        gpdest.Transform(m);
        //Create the Bitmap
        clipped = new Bitmap(width, height);
        //Draw on the Bitmap
        using (Graphics g = Graphics.FromImage(clipped))
        {
            GraphicsPath gpgdi = new GraphicsPath();
            g.SetClip(gpdest);
            g.DrawImage(source, -x, -y);
        }

你可以使用图形。剪辑指定一个自定义的剪辑区域(从GraphicsPath)从你的"源"位图/图像创建,然后重新绘制它在另一个缓冲区/临时图形对象,应该给你想要的结果。

这不是最有效的解决方案,但它至少可以让您朝着正确的方向前进。