问题
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