Click here to Skip to main content
15,912,665 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all,
I want to draw lines over an existing image in a picturebox (VS2008, .net3.5). No issues as far as drawing it once is concerned. But I want these lines to be shifted to the mouse position as I move in the picture box. So I wrote the following code in the PictureBox_MouseMove event:-

Graphics g = pictureBox1.CreateGraphics();
            g.Clear(Color.Transparent);
            Pen p = new Pen(Color.Red, 2.0f);

            for (int n = 1; n <= 50; n++)
            {
                g.DrawLine(p, n * (Cursor.Position.X), Cursor.Position.Y - 30.0f, n * (Cursor.Position.X), Cursor.Position.Y + 30.0f);

            }

The code is working fine when there is no image in the PictureBox. Whern there is an image in the picturebox, the lines are getting drawn, but before that the image already in the picturebox is getting erased (g.Clear(Color.Transparent)).
I tried to keep the image in a panel and run the code in Panel_MouseMove event, but to no avail.
How do I draw these lines while keeping the existing image intact?
GeoNav
Posted

1 solution

Firstly, when you create a graphics item, you are responsible for destroying it. They are a (very) finite resource, and you must not create them, use them and discard them as the whole system will run out, well before the GC gets round to disposing of them for you. The best way is to put them in a using block:
using(Graphics g = pictureBox1.CreateGraphics())
   {
   g.Clear(Color.Transparent);
   Pen p = new Pen(Color.Red, 2.0f);

   for (int n = 1; n <= 50; n++)
       {
       g.DrawLine(p, n * (Cursor.Position.X), Cursor.Position.Y - 30.0f, n * (Cursor.Position.X), Cursor.Position.Y + 30.0f);

       }
   }

Secondly, don't do what you are trying to do. A Picture box is a dumb animal, and when you manually erase it's content as you do in the example you gave it doesn't know to re-draw it. You can force it to redraw it's picture, but then it will overwrite your lines.
Instead, use a Panel, and handle the Paint event. Draw the picture yourself - using the Graphics property of the PaintEventArgs "e" so you don't have to worry about destroying it - then on the same graphics context draw your lines. Simples!
 
Share this answer
 
Comments
koool.kabeer 5-Aug-10 9:24am    
g.Clear(Color.Transparent) is doing the trick...
nice question and nice reply...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900