C#: Draw one Bitmap onto Another, with Transparenc

2020-05-25 17:50发布

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.

3条回答
地球回转人心会变
2楼-- · 2020-05-25 18:18

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);
查看更多
Fickle 薄情
3楼-- · 2020-05-25 18:22

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;
            }
        }
    }
查看更多
姐就是有狂的资本
4楼-- · 2020-05-25 18:28

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

查看更多
登录 后发表回答