C# How can I merge two Bitmaps?

2019-09-01 16:15发布

问题:

I'm trying to find a way to merge two Bitmaps together in a Paint event. My code looks like this:

private void GraphicsForm_Paint(object sender, PaintEventArgs e)
{
    try
    {
        Bitmap1 = new Bitmap(1366, 768);
        Bitmap2 = new Bitmap(1366, 768);
        OutputBitmap = ...//and this is where I've stuck :(
    }
    catch
    {
    }
}

The problem is more problematic, because the Graphics object which draws onto Bitmap2 is in an other class. I also want Bitmap2 to be drawn behind Bitmap1 on the OutputBitmap.

Can anyone give me a good advice how to merge these two Bitmaps (behind eachother, but) onto one output bitmap?

Thanks :)

回答1:

Assuming your bitmaps have transparent areas, try creating one bitmap and draw the other two bitmaps into it in the order you want:

private Bitmap MergedBitmaps(Bitmap bmp1, Bitmap bmp2) {
  Bitmap result = new Bitmap(Math.Max(bmp1.Width, bmp2.Width),
                             Math.Max(bmp1.Height, bmp2.Height));
  using (Graphics g = Graphics.FromImage(result)) {
    g.DrawImage(bmp2, Point.Empty);
    g.DrawImage(bmp1, Point.Empty);
  }
  return result;
}