Click here to Skip to main content
15,945,119 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
Goal: To draw shapes by pixels.
Problem: WPF is DPI aware and it leads to lots of problems like stroke thickness more than 1 pixel, blurry edges, clipped geometry doesn't match drawn geometry despite the geometry is same.
Warning: None out the next code works:
RenderOptions.SetEdgeMode(canvas, EdgeMode.Aliased);
canvas.SnapsToDevicePixels = true;
canvas.UseLayoutRounding = true;
RenderOptions.SetBitmapScalingMode(canvas, BitmapScalingMode.NearestNeighbor);

Question: How to fix the problem to draw by pixels?
Note: The goal is not to draw by setting pixels separately, the goal is to draw shapes without all these problems caused by "DPI awareness".
Updated 30-Jul-15 4:20am
Afzaal Ahmad Zeeshan 30-Jul-15 9:41am    
You cannot do so in WPF, WPF abstracts the actual device pixels from your application. Is this homework or assignment?
Ziya1995 30-Jul-15 10:17am    
> Is this homework or assignment?
It is an ability i wanna get to create glow effect.
WPF lacks this ability and that is why the same geometry clips and draws differently, clipped geometry doesn't match drawn geometry despite the fact the geometry is same. As a result i can't get the glow effect. The test was done using shapes.
So it is not homework, it is a very serious problem because of which i can't create the glow effect.

I have read about setting DPI size, can it solve it?
But you said i can not do so in WPF. May be i have a chance by setting DPI size if it is possible?

Share this answer
Note: The code was posted buggy due to the forum, fix it before to use.

Goal: To scale to fit a target DPI.

Specific code:
canvas.RenderTransform = new MatrixTransform(

Code example:
    public partial class MainWindow : Window
        public MainWindow()
            this.Loaded += MainWindow_Loaded;
<pre><code>    Canvas canvas;

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
        canvas = new Canvas();
        canvas.Background = Brushes.Black;
        this.Content = canvas;

        RenderOptions.SetEdgeMode(canvas, EdgeMode.Aliased);
        //canvas.SnapsToDevicePixels = true; // doesn't affect

        canvas.RenderTransform = new MatrixTransform(



    int i = 0;
    int add = 2;

    private void Shape()

        for (int i = 0; i < 20 * add; i += add)
            Line line = new Line();
            line.X1 = 30;
            line.Y1 = 30 + i;
            line.X2 = 100;
            line.Y2 = 30 + i;
            line.Stroke = Brushes.White;
            line.StrokeThickness = 1;


Codeproject source[^].

Msdn source[^].
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900