C#: Draw one Bitmap onto Another, with Transparenc

2020-05-25 17:42发布

问题:

I have two Bitmaps, named largeBmp and smallBmp. I want to draw smallBmp onto largeBmp, then draw the result onto the screen. SmallBmp's white pixels should be transparent. Here is the code I'm using:

public Bitmap Superimpose(Bitmap largeBmp, Bitmap smallBmp) {
    Graphics g = Graphics.FromImage(largeBmp);
    g.CompositingMode = CompositingMode.SourceCopy;
    smallBmp.MakeTransparent();
    int margin = 5;
    int x = largeBmp.Width - smallBmp.Width - margin;
    int y = largeBmp.Height - smallBmp.Height - margin;
    g.DrawImage(smallBmp, new Point(x, y));
    return largeBmp;
}

The problem is that the result winds up transparent wherever smallBmp was transparent! I just want to see through to largeBmp, not to what's behind it.

回答1:

CompositingMode.SourceCopy is the problem here. You want CompositingMode.SourceOver to get alpha blending.



回答2:

Specify the transparency color of your small bitmap. e.g.

Bitmap largeImage = new Bitmap();
Bitmap smallImage = new Bitmap();
--> smallImage.MakeTransparent(Color.White);
Graphics g = Graphics.FromImage(largeImage);
g.DrawImage(smallImage, new Point(10,10);


回答3:

Winform copy image on top of another

    private void timerFFTp_Tick(object sender, EventArgs e)
    {
        if (drawBitmap)
        {
            Bitmap bitmap = new Bitmap(_fftControl.Width, _fftControl.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);   
            _fftControl.DrawToBitmap(bitmap, new Rectangle(0, 0, _fftControl.Width, _fftControl.Height));
            if (!fDraw)
            {
                bitmap.MakeTransparent();
                Bitmap fftFormBitmap = new Bitmap(_fftForm.BackgroundImage);
                Graphics g = Graphics.FromImage(fftFormBitmap);
                g.DrawImage(bitmap, 0, 0);
                _fftForm.BackgroundImage = fftFormBitmap;
            }
            else
            {
                fDraw = false;
                _fftForm.Width = bitmap.Width + 16;
                _fftForm.Height = bitmap.Height + 48;
                _fftForm.BackgroundImage = bitmap;
            }
        }
    }