95
votes

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#.

9
I made a control which plots some very nice scientific graphs (with added capabilities I need not available in any commercial controls). I can plot a data point with and X or a + or a small box. But for unimportant data, I just want a single pixel.Mark T
All the answers I see seem like they really are overkill for a single pixel? Why does it seem easier just to do a buffer[y*width+x]=color;NoMoreZealots

9 Answers

115
votes

This will set a single pixel:

e.Graphics.FillRectangle(aBrush, x, y, 1, 1);
18
votes

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?

18
votes

Just to show complete code for Henk Holterman answer:

Brush aBrush = (Brush)Brushes.Black;
Graphics g = this.CreateGraphics();

g.FillRectangle(aBrush, x, y, 1, 1);
10
votes

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.

2
votes

MSDN Page on GetHdc

I think this is what you are looking for. You will need to get the HDC and then use the GDI calls to use SetPixel. Note, that a COLORREF in GDI is a DWORD storing a BGR color. There is no alpha channel, and it is not RGB like the Color structure of GDI+.

This is a small section of code that I wrote to accomplish the same task:

public class GDI
{
    [System.Runtime.InteropServices.DllImport("gdi32.dll")]
    internal static extern bool SetPixel(IntPtr hdc, int X, int Y, uint crColor);
}

{
    ...
    private void OnPanel_Paint(object sender, PaintEventArgs e)
    {
        int renderWidth = GetRenderWidth();
        int renderHeight = GetRenderHeight();
        IntPtr hdc = e.Graphics.GetHdc();

        for (int y = 0; y < renderHeight; y++)
        {
            for (int x = 0; x < renderWidth; x++)
            {
                Color pixelColor = GetPixelColor(x, y);

                // NOTE: GDI colors are BGR, not ARGB.
                uint colorRef = (uint)((pixelColor.B << 16) | (pixelColor.G << 8) | (pixelColor.R));
                GDI.SetPixel(hdc, x, y, colorRef);
            }
        }

        e.Graphics.ReleaseHdc(hdc);
    }
    ...
}
2
votes

Drawing a Line 2px using a Pen with DashStyle.DashStyle.Dot draws a single Pixel.

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        using (Pen p = new Pen(Brushes.Black))
        {
            p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
            e.Graphics.DrawLine(p, 10, 10, 11, 10);
        }
    }
1
votes

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.

1
votes

If you are drawing on a graphic with SmoothingMode = AntiAlias, most drawing methods will draw more than one pixel. If you only want one pixel drawn, create a 1x1 bitmap, set the bitmap's pixel to the desired color, then draw the bitmap on the graphic.

using (var pixel = new Bitmap(1, 1, e.Graphics))
{
    pixel.SetPixel(0, 0, color);
    e.Graphics.DrawImage(pixel, x, y);
}
0
votes

There are a lot of answers here, but they're all pretty awful :(

The absolute best method is to create a bitmap and pass it an intptr (pointer) to an existing array. This allows the array and the bitmap data to share the same memory ... no need to 'Bitmap.lockbits'/'Bitmap.unlockbits' (slow).

Here's the broad outline...

  1. Mark your function 'unsafe' and set your projects build settings to allow 'unsafe' code! (c# pointers)
  2. Create your array[,]. Either using Uint32's, Bytes or a Struct that permits access to by both Uint32 OR individual Uint8's (By using explicit field offsets)
  3. Use "System.Runtime.InteropServices.Marshal.UnsaveAddrOfPinnedArrayElement" to obtain the Intptr to the start of the array.
  4. Create the Bitmap using the constructor that takes an Intptr and Stride. This will overlap the new bitmap with the existing array data.

You now have permanent direct access to the pixel data!

The underlying array

The underlying array would likely be a 2D array of a user-struct 'Pixel'. Why? Well... Structs can allow multiple member variables to share the same space by using explicit fixed offsets! This means that the struct can have 4 single-bytes members (.R, .G, .B and .A), and 3 overlapping Uint16's (.AR, .RG and ,GB) ... and a single Uint32 (.ARGB) ... this can make colour-plane manipulations MUCH faster.

As R,G,B, AR,RG,GB and ARGB all access different parts of the same 32-bit pixel you can manipulate pixels in a highly flexible way!

Because the array of Pixel[,] shares the same memory as the Bitmap itself, Graphics operations immediately update the Pixel array - and Pixel[,] operations on the array immediately update the bitmap! You now have multiple ways of manipulating the bitmap ;)

Flexible AND fast ;)

Remember, by using this technique you do NOT need to use 'lockbits' to marshal the bitmap data in and out of a buffer... which is good, because lockbits is very VERY slow.

You also don't need to use a brush and call complex framework code capable of drawing patterned, scalable, rotatable, translatable, aliasable, rectangles... just to write a single pixel Trust me - all that flexibility in the Graphics class makes drawing a single pixel using 'Graphics.FillRect' a very slow process.

Other benefits...

Super-smooth scrolling! Your Pixel buffer can be larger than your canvas/bitmap, in both height and width! This enables efficient scrolling!!!!

How?

Well, when you create a Bitmap from the array you can point the bitmaps upper-left coordinate at some arbitrary [y,x] coordinate by taking the IntPtr of that Pixel[,].

Then, by deliberately setting the Bitmaps 'stride' to match width of the array (not the width of the bitmap) you can render a predefined subset rectangle of the larger array... whilst drawing (ahead of time) into the unseen margins! This is the principle of "offscreen drawing" in smooth scrollers.

Finally

You REALLY should wrap the Bitmap and Array into a FastBitmap class. This will help you control the lifetime of the array/bitmap pair. Obviously, if the array goes out of scope or is destroyed - the bitmap will be left pointing at an illegal memory address. By wrapping them up in a FastBitmap class you can ensure this can't happen...

... it's also a really handy place to put the various utilities you'll inevitably want to add... such as scrolling, fading, working with colour planes, etc.

Remember:

  1. Creating Bitmaps from a MemoryStream is very slow
  2. Using Graphics.FillRect to draw pixels is painfully inefficient
  3. Accessing underlying bitmap data with lockpixels/unlockpixels is very slow
  4. And, if you're using 'System.Runtime.InteropServices.Marshal.Copy', just stop!

Mapping the Bitmap onto some existing array memory is the way to go. Do it right, and you'll never need/want to use a framework Bitmap again :)

You're welcome ;)