First of all, don't use
PictureBox
for such purpose. Even though you can, it won't help you at all, will only add some hassles and eat up a bit of extra resources, giving nothing in return. This control in nothing but a shortcut for very simple cases. You need to draw immediately on some control (a custom one derived from
System.Windows.Forms.Control
,
Panel
or the like). I'll explain how:
How do I clear a panel from old drawing[
^],
draw a rectangle in C#[
^],
Append a picture within picturebox[
^].
See also these past answers:
Drawing Lines between mdi child forms[
^],
capture the drawing on a panel[
^],
What kind of playful method is Paint? (DataGridViewImageCell.Paint(...))[
^],
How to speed up my vb.net application?[
^].
Now when it's clear, you have a choice: you can draw your pixels immediately in
OnPaint
(please see below), or you might need to do it on
Bitmap
. You can even make both in the same method. You only need to abstract out the instance of
System.Drawing.Graphics
, make it a parameter of drawing function. You will take it parameter from event args, in case of
OnPaint
, of from bitmap — this way:
http://msdn.microsoft.com/en-us/library/system.drawing.graphics.fromimage.aspx[
^].
Now, the problem could be
performance. If you really need to draw the image pixel-by-pixel using
SetPixel
, and there are many pixels,
it will be prohibitively slow, don't do it! In this case, always use bitmap.
The only fast way is using
System.Drawing.Bitmap.LockBits
:
http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.lockbits.aspx[
^].
—SA