1

I am using the following code in an attempt to draw on an image inside a picture box, however the changes are not rendering on the form itself.

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            if (drawMode)
            {
            Graphics g = Graphics.FromImage(pictureBox1.Image);
            RectangleF rectf = new RectangleF(10, 10, 100, 100);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.DrawString("yourText", new Font("Tahoma", 22), Brushes.Green, rectf);
            g.Flush();
....

EDIT: Code is now in the PaintEventHandler for the picturebox1 object.

ddoor
  • 5,819
  • 9
  • 34
  • 41
  • As the answer says, the call to Invalidate erases whatever you do and replaces it with the original image. You need to make sure that you modify the image every time the control repaints itself, or save it to a new bitmap and use that as the picturebox image. – Ron Beyer Apr 30 '15 at 03:42
  • Thanks @RonBeyer - I have altered this now but have had no luck. Am I missing anything else? – ddoor Apr 30 '15 at 03:50
  • Yes, first in the paint method call base.Paint(sender, e). Then in your code don't use Graphics.FromImage, use g = e.Graphics. Then it should work. – Ron Beyer Apr 30 '15 at 03:53
  • Also: The `Paint` event does not draw __an image in the PictureBox__. Instead it draws __onto the surface__ of the `PicureBox`. To see the difference [look here](http://stackoverflow.com/questions/27337825/picturebox-paintevent-with-other-method/27341797?s=2|0.0389#27341797). To see an example using the __three layers__ of a `PictureBox` see [here](http://stackoverflow.com/questions/29819440/painting-to-panel-after-update-call/29822012#29822012) – TaW Apr 30 '15 at 06:53

1 Answers1

1

I'm not too sure why you are doing that or whether this is correct or not. But normally, you'd want to do the drawing inside the Paint event of the PictureBox...

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    //draw here, but DONOT call the Invalidate method
}

if you want to do the drawing only when the form receives some user input such as a button click. Use a boolean flag to determine when and what to draw inside the Paint event. Then inside the button click handler, invalidate the the PictureBox

Leo
  • 14,625
  • 2
  • 37
  • 55
  • Thanks, I have since adjusted my code but the text is yet to show up. I can confirm its getting called in the PaintEventHandler code – ddoor Apr 30 '15 at 03:46
  • Turns out my co-ordinates for testing were a bit off, thanks :) – ddoor Apr 30 '15 at 03:53