tags:

views:

176

answers:

5

I need to draw 100 lines between 100 semi-random points in a 800x800 pixel square on the screen.

I've been using the built-in drawlines & drawrecangles functions inside of .NET, but my drawing gets erased everytime the form paints.

So, I've been thinking about perhaps drawing to an in-memory bitmap, but I'm not sure if that's a good solution.

Any tips?

+2  A: 

It is a good idea. You draw to a bitmap and the bitmap is drawn in your form. Just call a redraw (or equivalent) after modifiing your bitmap.

Burkhard
+3  A: 

Not only is this a good idea, but also it has a name (double buffering). Do your drawing on a form-level Bitmap, and then in your form's Paint event (actually it would be better to do this with a PictureBox on the form, and use it's Paint event) use the DrawImage method of the Graphics object to draw your Bitmap into the PictureBox.

A simpler way is just to create your Bitmap, draw on it, and then set the Bitmap as your PictureBox's Image property. This will automatically persist the image even when your form is repainted.

MusiGenesis
+2  A: 

It is not a good idea, assuming my machine's GDI+ performance is comparable. The Form class already supports double buffering through the DoubleBuffered property. It does a better job than you can do, assuming you don't dip into P/Invoke like it does.

My measurements:

  • 100 random lines, no double buffering: 68 msec
  • 100 random lines, double buffering: 2.6 msec
  • Graphics.DrawImage 800x800x32PArgb, no double buffering, empty OnPaintBackground: 9.8 msec

This will of course change when you draw more than 400 lines. To get the perf that WF's double buffering gives you you'd have to use the BufferedGraphics class. It is very unfriendly.

Hans Passant
+1  A: 

You can draw on a bitmap to make it persistent, or you can use the paint event to draw it on the form.

To draw on a bitmap (picture box Picture1, in this example):

dim g as graphics
g = Graphics.FromImage(Picture1.Image)
g.DrawRectangle(...)

To use the paint event:

Private Sub Form1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles Me.Paint
e.Graphics.DrawRectangle(...)
end sub
xpda
A: 

While BufferedGraphics may be unfriendly, this guy explains it well with a base class you can use for your own controls.

rohancragg