views:

1486

answers:

4

I'm stuck trying to turn on a single pixel on a Windows Form.

graphics.DrawLine(Pens.Black, 50, 50, 51, 50); // draws two pixels

graphics.DrawLine(Pens.Black, 50, 50, 50, 50); // draws no pixels

The API really should have a method to set the color of one pixel, but I don't see one.

I am using C#.

+4  A: 

The Graphics object doesn't have this, since it's an abstraction and could be used to cover a vector graphics format. In that context, setting a single pixel wouldn't make sense. The Bitmap image format does have GetPixel() and SetPixel(), but not a graphics object built on one. For your scenario, your option really seems like the only one because there's no one-size-fits-all way to set a single pixel for a general graphics object (and you don't know EXACTLY what it is, as your control/form could be double-buffered, etc.)

Why do you need to set a single pixel?

Adam Robinson
+2  A: 

Apparently DrawLine draws a line that is one pixel short of the actual specified length. There doesn't seem to be a DrawPoint/DrawPixel/whatnot, but instead you can use DrawRectangle with width and height set to 1 to draw a single pixel.

Rytmis
Nice try, but with size 1 it draws 2x2 pixels. (Draw it next to a line, and you can see it is twice as wide.) And with size zero, of course, it draws nothing.
Mark T
Right, my mistake. :) Good thing FillRectangle does the trick.
Rytmis
+12  A: 

This will set a single pixel:

e.Graphics.FillRectangle(aBrush, x, y, 1, 1);
Henk Holterman
Who would have guessed that DrawRectangle draws a 2x2 but FillRectange draws a 1x1 with the same arguments? Thanks.
Mark T
@Mark: It does make a sort of sense... DrawRectangle says "draw an outline starting at x and y of this width and height," so it draws both the start and end points (x,y; x+1,y;x,y+1; x+1,y+1) and lines between them. FillRectangle says "draw a solid surface starting at x,y of this width and height." Incidentally, FillRectangle takes a Brush, not a Pen.
R. Bemrose
+2  A: 

Where I'm drawing lots of single pixels (for various customised data displays), I tend to draw them to a bitmap and then blit that onto the screen.

The Bitmap GetPixel and SetPixel operations are not particularly fast because they do an awful lot of boundschecking, but it's quite easy to make a 'fast bitmap' class which has quick access to a bitmap.

Will Dean