如何将多个pictureBox图像添加到Panel的背景图像?

时间:2012-10-07 18:57:45

标签: c# winforms panel

Hello stackoverflow社区。

我不想将每个pictureBoxes图像绘制到Panel1,而是想将每个pictureBox图像(pictureBox1,pictureBox2,pictureBox3)添加到Bitmap,然后将Bitmap设置为Panel1的背景图像。

这可能吗? 谢谢 enter image description here

1 个答案:

答案 0 :(得分:2)

这是我发现将多个图像组合成一个位图的方法

public static System.Drawing.Bitmap CombineBitmap(Image[] files)
        {
            //read all images into memory
            List<System.Drawing.Bitmap> images = new List<System.Drawing.Bitmap>();
            System.Drawing.Bitmap finalImage = null;

            try
            {
                int width = 0;
                int height = 0;

                foreach (Image image in files)
                {
                    //create a Bitmap from the file and add it to the list
                    System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);

                    //update the size of the final bitmap
                    width += bitmap.Width;
                    height = bitmap.Height > height ? bitmap.Height : height;

                    images.Add(bitmap);
                }

                //create a bitmap to hold the combined image
                finalImage = new System.Drawing.Bitmap(width, height);

                //get a graphics object from the image so we can draw on it
                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalImage))
                {
                    //set background color
                    g.Clear(System.Drawing.Color.Black); // Change this to whatever you want the background color to be, you may set this to Color.Transparent as well

                    //go through each image and draw it on the final image
                    int offset = 0;
                    foreach (System.Drawing.Bitmap image in images)
                    {
                        g.DrawImage(image,
                          new System.Drawing.Rectangle(offset, 0, image.Width, image.Height));
                        offset += image.Width;
                    }
                }

                return finalImage;
            }
            catch (Exception ex)
            {
                if (finalImage != null)
                    finalImage.Dispose();

                throw ex;
            }
            finally
            {
                //clean up memory
                foreach (System.Drawing.Bitmap image in images)
                {
                    image.Dispose();
                }
            }
        }

你需要创建一个图像数组才能使用,然后你可以尝试这个

        Image[] Files = new Image[3]; // Create a new array of maximum 3 indices
        Files[0] = pictureBox1.Image;
        Files[1] = pictureBox2.Image;
        Files[2] = pictureBox3.Image;
        panel1.BackgroundImage = CombineBitmap(Files); //Add the combined bitmap to the BackgroundImage

谢谢,

祝你有个美好的一天,对于误会感到抱歉:)