Problem with refreshing picture

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Potr Milczarek
    New Member
    • Nov 2010
    • 3

    #1

    Problem with refreshing picture

    Hi,

    I created small application, which is suppose to draw objects on jpg file ( loaded into picturebox ). Coordinates of objects are provided by user ( by clicking on picturebox ). Here are some code samples:

    Code:
     public void ryspkt(MouseEventArgs e)
            {
                if (pictureBox1.Image != null)
                {
    
                    if (e.Button == MouseButtons.Left)
                    {
                      rect[nrprs++] = new Rectangle(e.X, e.Y,2,2);
                      pictureBox1.Invalidate();
                    }
    Code:
           private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
            {
                ryspkt(e);
            }
    Code:
     private void pictureBox1_Paint(object sender, PaintEventArgs e)
            {
                    //g = e.Graphics;
                    g = Graphics.FromImage(pictureBox1.Image);
                    for (int i = 0; i < nrprs; i++)
                        {
                            g.FillEllipse(b, rect[i]);
                        }
            }
    So - the problem is that ellipses are drawn with delay - I mean that first is drawn on 2nd click, 2nd ellipse on 3rd click, and so on. I assume that there is issue with validating picturebox, but I can't find what I'm doing wrong :/

    There is no issue at all if I switch from "g = Graphics.FromIm age(pictureBox1 .Image)" to "g = e.Graphics" but if I do this I can't save image properly ( drawn object just disappear ).

    Any suggestions ? :)

    Regards,
    Piotr
  • Potr Milczarek
    New Member
    • Nov 2010
    • 3

    #2
    Ok, I fixed it :) Refreshing picturebox before using invalidate was sufficient.

    However, I have secong question - is there any simple way to erase drawn ellipses ( and keep image ) when I click "clear" button ?

    Thanks,
    Piotr

    Comment

    • GaryTexmo
      Recognized Expert Top Contributor
      • Jul 2009
      • 1501

      #3
      No, I don't think you can erase in this fashion. You're drawing right onto the image so once once drawn, it's there.

      However, you can do a few things...

      1) Keep a copy of the original image. When you want to clear, just restore the image itself.

      2) Don't draw on the actual image at all. Keep track of the draw operations in a list, then in the Paint method draw the picture, then the various other things on top of that using the graphics object for whatever control you're painting on. This will let you undo/redo if need be as well.

      Comment

      • Potr Milczarek
        New Member
        • Nov 2010
        • 3

        #4
        1st method worked perfectly, thank you very much !

        Comment

        Working...