Erase to Transparency

﹥>﹥吖頭↗ 提交于 2020-01-03 02:54:32

问题


So I'm trying to make a 32x32 block back to transparent but everytime I try to set it to transparent it just keeps what ever is already there, I want to erase what's on the image to transparent, here's my code I tried.

    public Bitmap erase_tile(Bitmap bitmap, int x, int y)
    {
        Graphics device = Graphics.FromImage(bitmap);

        Brush brush = new SolidBrush(Color.FromArgb(0, Color.White));

        device.FillRectangle(brush, new Rectangle(x * 32, y * 32, 32, 32));
        return bitmap;
    }

回答1:


All transparency is going to be accomplished via functionality on the Bitmap class. The Graphics class is geared toward drawing, and drawing Color.Transparent is essentially a no-op.

You can use Bitmap.SetPixel() with Color.Transparent to set individual pixels.

Or you can do something like this, where you use Graphics to paint a dummy color which you will then instruct the bitmap to use as the transparent color.

using (var graphics = Graphics.FromImage(bmp))
{
    graphics.FillRectangle(Brushes.Red, 0, 0, 64, 64);
    graphics.FillRectangle(Brushes.Magenta, 16, 16, 32, 32);
}
bmp.MakeTransparent(Color.Magenta);



回答2:


While I was searching for the same solution, I wasn't able to find the exact answer, so after some experiments I came across SetCompositingMode and it made the trick (refer to Using Compositing Mode to Control Alpha Blending for full details).

Here is a working code in C++ to demonstrate the approach (it needs some tuning to be re-used in C#):

void SetTransparent(Gdiplus::Image* image, IN INT x, IN INT y, IN INT width, IN INT height)
{
    Gdiplus::Graphics graph(image);
    graph.SetCompositingMode(Gdiplus::CompositingModeSourceCopy);
    Gdiplus::SolidBrush transparent(0);
    graph.FillRectangle(&transparent, x, y, width, height);
}


来源:https://stackoverflow.com/questions/17073357/erase-to-transparency

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!