C#:将一个位图绘制到另一个位图上,支持透明度

26

我有两个位图,分别命名为largeBmp和smallBmp。我想要在largeBmp上绘制smallBmp,然后将结果绘制到屏幕上。SmallBmp的白色像素应该是透明的。这里是我正在使用的代码:

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;
}
问题在于,无论smallBmp哪里是透明的,结果都会变成透明的!我只想看到largeBmp的背景,而不是它后面的内容。
3个回答

28

CompositingMode.SourceCopy 是问题所在。你需要使用 CompositingMode.SourceOver 来获得 alpha 混合。


3

指定您的小位图的透明颜色。例如:

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

不,它已经将白色转换为透明了。问题是透明将两个图像都剪切穿透了。 - Paul A Jungwirth

0

Winform复制图像叠加在另一张图片上

    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;
            }
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接