简体   繁体   中英

Getting the image in a PictureBox control with the lines drawn using a graphics object

I have troubles understanding how the graphics objects are drawn. Suppose to have this function:

private void DrawLineOnOverlay()
{
        using (var g = pictureBox.CreateGraphics())
        {
            g.DrawLine(OverlayPen, cursorStartx, cursorStarty, cursorEndx, cursorEndy);
        }         
}

to draw simple lines in a pictureBox control where you have already done this:

pictureBox.Image = BitmapToBeLoaded;    // Load an 8-bit indexed Bitmap 

My understanding is that both the image loaded and the pixel drawn using the graphics object are parte of the very same image: pictureBox.Image

but this:

Bitmap graphic = pictureBox.Image;
if (graphic  != null )  
{               
    graphic = new Bitmap (pictureBox.Image);       
    graphic.Save( "C:\\packed.png", ImageFormat.Png);       
}

does not work: the image saved does not show the lines drawn in red over the image. Why this? What is wrong?

If you want to be able to save your drawings then you need to draw them on a surface and then save the surface. Usually, drawing on PictureBox canvas would not let you save the image because the Image class has nothing to do with drawings. Image is just an abstract class on top of Bitmap which is able to load a GDI+ supported image file and then present it in PictureBox . Drawings are done on a GDI+ drawing surface which is Graphics object.

You can create a surface:

Bitmap surface = new Bitmap(640, 480);
Graphics g = Graphics.FromImage(surface);

using (var OverlayPen = new Pen(Color.Red))
{
  g.DrawLine(OverlayPen, cursorStartx, cursorStarty, cursorEndx, cursorEndy);
}

If you want to show drawings, you can set Surface as PictureBox 's image. And remember to use using pattern when you are creating graphical objects like pens or brushes because if you don't they're going to stay on memory all the way to the end of the context and they may cause overflow at some points.

To save then:

surface.Save( "C:\\packed.png", ImageFormat.Png);

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