Question

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.

Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top