WPF - canvas height in pixels

岁酱吖の 提交于 2019-12-18 01:32:10

问题


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.


回答1:


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?



来源:https://stackoverflow.com/questions/611427/wpf-canvas-height-in-pixels

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!