Paste the contents of a Bitmap into a PictureBox

旧巷老猫 提交于 2020-01-06 04:37:47

问题


I'm currently writing a little paint application where the user is able to draw on a Panel. I am working on the select tool and want to be able to select a certain area of the Panel, and then paste this selected area directly into a PictureBox that I have just to the right of the Panel.

My problem is that my code at the moment is not working correctly, when I try to paste the Bitmap that I am creating from the panel I am getting a big red X in the PictureBox instead of the actual image. I know that the image is copying to the Bitmap correctly because I tried putting some code around it to save it to disk as a jpeg and then look at the image, and it is all displaying fine.

Here is my code:

private void tbCopy_Click(object sender, EventArgs e)
{
    int width = selectList[0].getEnd().X - selectList[0].getInitial().X;
    int height = selectList[0].getEnd().Y - selectList[0].getInitial().Y;

    using (Bitmap bmp = new Bitmap(width, height))
    {
        pnlDraw.DrawToBitmap(bmp, new System.Drawing.Rectangle(
                                      selectList[0].getInitial().X,
                                      selectList[0].getInitial().Y, 
                                      width, height));
        pbPasteBox.Image = bmp;             
    }
}   

the width and height are just the dimensions of the area that I want to copy, and selectList is a List that contains one object which contains the coordinates of the area I want to copy.

Any help would be greatly appreciated.


回答1:


Your problem is the using(){} when the code inside the using braces has completed the object inside the () is disposed of as it is deemed no longer needed.

Simply removing the brace to just have Bitmap bmp = new Bitmap(width, height) should solve your problem



来源:https://stackoverflow.com/questions/16030269/paste-the-contents-of-a-bitmap-into-a-picturebox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!