문제

I'm trying to "draw" areas of transparency onto a bitmap -- like cutting holes in the image.

The following code does not draw a line of transparency because drawing a transparent line onto a bitmap of course blends instead of replaces. (Why the default is to do the more complicated of the two drawing operations, makes no sense.)

Bitmap myBitmap = new Bitmap(50, 50);
Graphics g = Graphics.FromImage(myBitmap);
g.FillRectangle(Brushes.Black, 0, 0, 50, 50);
g.FillEllipse(Brushes.Transparent, 25, 0, 25, 25); //Does nothing
g.DrawLine(Pens.Transparent, 0, 0, 50, 50); //Does nothing

How would I modify this so that a transparent circle and line replace what's in the bitmap instead of blending?

(Note that this is the trivial case of "drawing" complete transparency. The end I'm going toward is the ability to "draw" modifying the alpha channel only without creating my own pixel by pixel operation. Being able to do complete transparency will suffice though.)


Following answer in article suggested as a duplicate, I've also tried the following (which does not work)

        base.OnPaint(e);
        Bitmap myBitmap = new Bitmap(50, 50);
        e.Graphics.FillRectangle(Brushes.Black, 0, 0, 50, 50);
        Graphics g = Graphics.FromImage(myBitmap);
        g.FillEllipse(new SolidBrush(Color.FromArgb(150, 125, 125, 125)), 25, 0, 25, 25);
        g.DrawLine(new Pen(Color.FromArgb(150,25,25,25)), 0, 0, 50, 50);
        g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
        e.Graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
        e.Graphics.DrawImage(myBitmap, 0, 0);

also tested this with SourceCopy

도움이 되었습니까?

해결책

This works totally fine for me

Bitmap bmp = new Bitmap(50, 50, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
using (Graphics g = Graphics.FromImage(bmp))
{
    g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
    g.FillRectangle(Brushes.Black, 0, 0, 50, 50);
    g.FillEllipse(Brushes.Transparent, 25, 0, 25, 25);
    g.DrawLine(Pens.Transparent, 0, 0, 50, 50);
    g.Flush();
}
bmp.Save("Test.bmp");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top