Daniel
Daniel

Reputation: 1357

Drawing interactively lines over a Bitmap

I need to allow to the user to draw lines over an bitmap. Lines should be drawn interactively, I mean something performed using typical code giving to the user a visual feedback about what is drawn:

private void MainPictureBox_MouseDown( object sender, MouseEventArgs e)
{
   DrawingInProgress = true ;                
   Origin = new Point (e.X, e.Y);              
}

private void MainPictureBox_MouseUp(object sender, MouseEventArgs e)
{          
   DrawingInProgress = false ;
}

private void MainPictureBox_MouseMove(object sender, MouseEventArgs e)
{
  if (!DrawingInProgress) return ;
  End = new Point (e.X, e.Y);
  using( Pen OverlayPen = new Pen( Color .Red, 1.0f))        
  using (Graphics g = MainPictureBox.CreateGraphics())        
  {
       g.DrawLine(OverlayPen, Origin, End);      
     }
}

Of course I keep track of the points using List.Add within MainPictureBox_MouseUp in order to draw lines in the Paint event (code not shown for the sake of simplicity)

Without the background image things could be done nicely simply overwriting the previous line with the background color, something like:

 g.DrawLine(BackgroundColorPen, Origin, PreviousEnd);     
 g.DrawLine(OverlayPen, Origin, End);     

but this is not possible with a not uniform background.

Invalidating the rectangle defined by the points: Origin, PreviousEnd then using Update() makes the rendering quite messy. I am wondering how to perform this task and those are possible ways to do so i am considering:

  1. Draw the lines over a transparent bitmap then draw the bitmap over the Picturebox. I guess that with big images this is simply unfeasible for performances reason.
  2. Using the Picture.BackgroundImage for the bitmap then drawing on the Picture.Image but I unable to figure out how this could really saave the day
  3. Using double buffering? How?
  4. Stacking a different control (a panel?) over the pictureBox, making it transparent (is it possible?) then drawing over it.

Could someone give a hint in the best direction? I am really getting lost.

Upvotes: 0

Views: 860

Answers (1)

Daniel
Daniel

Reputation: 1357

The solutions working for me has been the following:

  1. Create a transparent panel;
  2. Put it over the bitmap having them overlap completely;
  3. Draw on the panel using proper mouse events;
  4. There is no need to cancel the previous shape, of course: it was a misleading question. It is sufficient to distinguish permanent shapes recorded in proper lists fed to the Paint event from the transient shape previously drawn that will be not drawn again in the next Paint event;
  5. Make absolutely sure that all drawings are performed in the Paint event using the Graphics provided by the PaintEventArgs. Thanks to @HansPassant to have stressed this in a different post.

Upvotes: 0

Related Questions