简体   繁体   中英

How do I paint Pictureboxes to Panel?

I have 2 pictureboxes on a panel at two separate locations which will become Hidden after a certain time. I would like to paint the pictureboxes background image to the panel at the exact points in which the picturebox controls lay. I have looked at the MSDN library but I cannot seem to find out how to do this.

Thanks for any help

I would do this by creating another 2 pictureboxes in the same location as the originals but without any picture in them. That way they will always be in the same spot as the originals. You leave the dupes empty so they show the background.

You can do something similar to this:

Bitmap bitmap = new Bitmap(panel1.Size.Width, panel1.Size.Height);
using (Graphics g = Graphics.FromImage(bitmap))
{
    g.DrawImage(pictureBox1.BackgroundImage, new Rectangle(pictureBox1.Location, pictureBox1.Size));
    g.DrawImage(pictureBox2.BackgroundImage, new Rectangle(pictureBox2.Location, pictureBox2.Size));
    g.Flush();
}

pictureBox1.Visible = false;
pictureBox2.Visible = false;
panel1.BackgroundImage = bitmap;

Or you can try using this:

public class PanelEx : Panel
{
    public PictureBox PictureBox1 { get; set; }
    public PictureBox PictureBox2 { get; set; }
    public bool IsBackgroundDrawn { get; set; }

    protected override void OnPaintBackground(PaintEventArgs e)
    {
        if (!IsBackgroundDrawn)
        {
            IsBackgroundDrawn = true;
            base.OnPaintBackground(e);
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        if (PictureBox1 != null && PictureBox2 != null && !IsBackgroundDrawn)
        {
            Bitmap bitmap = new Bitmap(this.Size.Width, this.Size.Height);
            e.Graphics.DrawImage(PictureBox1.BackgroundImage, new Rectangle(PictureBox1.Location, PictureBox1.Size));
            e.Graphics.DrawImage(PictureBox2.BackgroundImage, new Rectangle(PictureBox2.Location, PictureBox2.Size));
            e.Graphics.Flush();

            PictureBox1.Visible = false;
            PictureBox2.Visible = false;
            this.BackgroundImage = bitmap;
            IsBackgroundDrawn = false;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM