使用其内切椭圆剪切位图的最佳方法是什么?

时间:2013-09-28 22:07:45

标签: c# .net gdi+ system.drawing

我想拍摄一个带有ARGB 32像素格式的位图并剪裁它,使其内切椭圆内的内容保留,椭圆外的任何内容都变成ARGB(0,0,0,0)。 我可以使用GetPixel和SetPixel以及一些三角函数以编程方式来确定哪个像素超出范围 - 但我怀疑有更好,更内置的方法来做它。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

感谢亚历山德罗·D·安德里亚指出该地区的一部分 - 我已经弄明白了其余部分:

    public Bitmap Rasterize()
    {
        Bitmap ringBmp = new Bitmap(width: _size.Width, height: _size.Height, format: PixelFormat.Format32bppArgb);

        //Create an appropriate region from the inscribed ellipse
        Drawing2D.GraphicsPath graphicsEllipsePath = new Drawing2D.GraphicsPath();
        graphicsEllipsePath.AddEllipse(0, 0, _size.Width, _size.Height);

        Region ellipseRegion = new Region(graphicsEllipsePath);

        //Create a graphics object from our new bitmap
        Graphics gfx = Graphics.FromImage(ringBmp);

        //Draw a resized version of our image to our new bitmap while using the highest quality interpolation and within the defined ellipse region
        gfx.InterpolationMode = Drawing2D.InterpolationMode.NearestNeighbor;
        gfx.SmoothingMode = Drawing2D.SmoothingMode.HighQuality;
        gfx.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality;
        gfx.PageUnit = GraphicsUnit.Pixel;
        gfx.Clear(Color.Transparent);
        gfx.Clip = ellipseRegion;
        gfx.DrawImage(image: _image, rect: new Rectangle(0, 0, _size.Width, _size.Height));

        //Dispose our graphics
        gfx.Dispose();

        //return the resultant bitmap
        return ringBmp;
    }

显然将PixelOffsetMode设置为HighQuality非常重要,否则DrawImage方法会裁剪部分结果图像。