Search code examples
c#pixelsystem.drawing

Quickly draw pixels in WinForm in a container


I have a sizable form and the location in which a pixel is drawn moves, I have a panel which is the desired image size 400,200 - how can I change individual pixels on this panel? I also need the fastest change possible.


Solution

  • GDI+ does not have a method to set a single pixel, however you can set a 1x1 rectangle to achieve the same effect in your OnPaint event. It feels somewhat like a hack, however there is no standard way of doing this.

    SolidBrush brush = new SolidBrush(Color.White);
    
    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        SetPixel(brush, e.Graphics, 10, 10, Color.Red);
    }
    
    public void SetPixel(SolidBrush brush, Graphics graphics, int x, int y, Color color)
    {
        brush.Color = color;
        graphics.FillRectangle(brush, x, y, 1, 1);
    }
    

    You could also access the bitmap directly and use it's GetPixel and SetPixel methods, however they are generally very slow if your pixels need to be updated quickly.