简体   繁体   中英

How to draw with replacement instead of blending

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM