Search code examples
c#wpfcanvasdrawingpixel

Why I can not draw pixel side by side pixel?


I want to draw a picture using Canvas in C#. I have to have control of color of every pixel of picture, so I'm drawing it using Rectangle.

public void AddPixel(Canvas canvas, double x, double y)
    {
        Rectangle rec = new Rectangle();
        Canvas.SetTop(rec, y);
        Canvas.SetLeft(rec, x);
        rec.Width = 1;
        rec.Height = 1;
        rec.Fill = new SolidColorBrush(Colors.Black);
        canvas.Children.Add(rec);
    }

It should be working, but when I want to check it and draw simply black picture:

for (int y = 0; y < 50; y++)
        {
            for (int x = 0; x < 50; x++)
            {
                AddPixel(MandelbrotCanvas, x, y);
            }
        }

I get something like this - rectangles with something like borders, space between pixels:

enter image description here

Why? Someone could help me draw a clearly black picture?


Solution

  • Your image reveals that there seems to be some level of supersampling (a method of spatial anti-aliasing) in place. Your 1px wide line becomes softer than it really is. Anti-aliasing helps with drawing angled lines that don't look "pixelated".

    Supersampled line (zoomed in):

    Anti-aliased line

    Aliased line:

    Aliased line

    Set the RenderOptions.EdgeModeProperty to make sure your rectangles aren't anti-aliased:

    rec.SetValue(RenderOptions.EdgeModeProperty, EdgeMode.Aliased);
    

    If that doesn't work, try adding setting the UIElement.SnapsToDevicePixels property:

    rec.SnapsToDevicePixels = true;
    

    I would imagine that this prevents subpixel rendering of your rectangles.