Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precise pixel movement in Canvas

Tags:

c#

.net

wpf

I am doing some sort of drawing software in WPF, and I have certain visual elements in a Canvas like for example Rectangles and Lines. I have implemented dragging of those elements around the Canvas to move them. The motion must be aligned to pixels, I read WPF uses points and not pixels so it has become a concern of mine to know whether my lines or rectangles are aligned to pixels. I tried using SnapsToPixels, but I'm not sure it will do the trick, or if it will do it when I'm moving the visuals around.

Finally, I must implement moving visuals with the keyboard, a single cursor stroke means move the visual exactly one pixel, how can I do this from the code behind? I assume doing something like:

Canvas.SetLeft(visual) = Canvas.GetLeft(visual) + 1;

Will only add one point to its position, and not one pixel, how can I move exactly one pixel in the Canvas?

Thank you very much.

like image 621
So Many Goblins Avatar asked Jul 29 '26 04:07

So Many Goblins


2 Answers

It might help to use SnapToDevicePixels for your canvas.

like image 115
Felice Pollano Avatar answered Jul 31 '26 19:07

Felice Pollano


Is this what you are looking for?

Matrix m =
    PresentationSource.FromVisual(Application.Current.MainWindow)
        .CompositionTarget.TransformToDevice;
double pixelSizeX = m.M11;
double pixelSizeY = m.M22;
like image 31
Emond Avatar answered Jul 31 '26 18:07

Emond



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!