Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - canvas height in pixels

Tags:

wpf

pixels

How can I determine the width in pixels for a canvas (which has a certain width)?

I have a bitmap in an AnimatedImage control, and I know the bitmap's width in pixels, and I want to scale the bitmap so that it horizontally fits exactly the canvas. How can i determine this scale?

Note: I do not need to use RenderTargetBitmap, because the bitmap is already loaded.

like image 611
melculetz Avatar asked Dec 10 '22 21:12

melculetz


1 Answers

In WPF units are device independent. The formula to figure out the actual pixel size of a unit is:

Pixels per WPF Unit = ConstantWPFUnit size * monitor DPI;

Size of your element in pixels = Pixels per WPF Unit * MyElement.ActualWidth

The constant WPF unit size is 1/96. If I remember correctly the monitor DPI can be found as properties in the class returned from SystemInformation.GetPrimaryMonitor or something similar.

ActualWidth of a FrameworkElement is in device-independent units and is the width the element actually takes up after layout takes place. Simply multiply this property by the pixels per WPF unit you calculate above and you'll have your answer.

I have a suspicion that you doing to much manual coding however. Stretching images and other visual elements in any desired way can usually be accomplished simply by setting properties on the control/brush in question. Have you tried making HorizontalAlignment="Stretch" and VerticalAlignment="Center" for the element that contains the bitmap?

like image 183
astonish Avatar answered Dec 26 '22 13:12

astonish