简体   繁体   English

图片框上的C#绘图,不是持久的

[英]C# drawing on picturebox, not persistent

I have a List<> object, "imagelist", that contains the paths of many images such as .png's. 我有一个List <>对象“ imagelist”,其中包含许多图像的路径,例如.png的路径。 Now, with the following code: 现在,使用以下代码:

private void paint_picture(PictureBox picture, string pathofpic)
    {
        Graphics g = picture.CreateGraphics();
        Bitmap drawnpic = null;
        if (imagelist.ContainsKey(picture.Name))
        {
            drawnpic = new Bitmap(pathofpic);
            g.DrawImage(drawnpic, 0, 0, picture.Size.Width, picture.Size.Height);
            imagelist[picture.Name] = pathofpic;
        }
        drawnpic.Dispose();
        g.Dispose();
    }

I call this every time the card's image is changed, but I can't seem to make the image persist on the picturebox, when I drag the picturebox across the form (for example, over other pictureboxes). 每当卡的图像更改时,我都会调用此方法,但是当我在窗体上拖动图片框(例如,在其他图片框上方)时,我似乎无法使图像保留在图片框上。 The click and drag code is just moving the picturebox with the mouse, not really relevant. 单击和拖动代码只是用鼠标移动图片框,并非真正相关。

I've tried invalidating the form when I de-select the image, but it doesn't do anything. 当我取消选择图像时,我尝试使表单无效,但它没有任何作用。

Is there something I'm missing? 有什么我想念的吗? Screenshot below, I dragged one image around the form and it overwrote the other images it moved across: 下面的屏幕快照,我在窗体上拖动了一张图像,并覆盖了它在其中移动的其他图像:

在此处输入图片说明

That's how painting works – you have to handle its Paint event and keep painting the same thing each time it needs repainting. 这就是绘画的工作方式–您必须处理其Paint事件,并在每次需要重新绘画时都继续绘画相同的东西。

What you can do is draw on top of your original image: 您可以做的是在原始图像上绘制:

Bitmap b = new Bitmap(picture.Image);

using (Graphics g = Graphics.FromImage(b)) {
    using (Bitmap drawnpic = new Bitmap(pathofpic)) {
        g.DrawImage(drawnpic, 0, 0, b.Width, b.Height);
    }
}

picture.Image = b;

Then you'd save the original image somewhere and probably use it instead of picture.Image in the new Bitmap line. 然后,将原始图像保存在某个位置,并在new Bitmap行中使用它代替picture.Image

And PascalCase for method names, please. 请使用PascalCase作为方法名称。 ;) ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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