WPF Pixels to desktop pixels

天涯浪子 提交于 2019-12-01 05:49:06

问题


I've been linked in the past to this response to a similar question on converting WPF pixel coordinates to desktop ones, however I'm not sure I understand the maths involved.

Astonish' answer states that "Pixels per WPF Unit = ConstantWPFUnit size * monitor DPI;" and that "The constant WPF unit size is 1/96."

In my case, I've taken the DPI from a graphics object which was created from the bitmap object (as I couldn't find the property the Astonish spoke of) that I created after taking a screenshot of the desktop, so I have:

Graphics g = Graphics.FromImage(bitmap);
float WpfUnit = (1 / 96) * g.DpiX;

Given that the DPI being returned from the graphics object is 96, I am left with

WpfUnit = (1 / 96) * 96 = 1

However, WpfUnit is coming out as 0 for some unknown (to me) reason. The only way I can see to fix this is to say

if(WpfUnit == 0) WpfUnit = 1;

And even that doesn't really fix the issue, as the height value and top values, when multiplied by the WpfUnit as suggested in the linked answer, have nothing done to them aside from being multiplied by 1.

So, in conclusion, I'm still stuck on converting WPF pixels to desktop pixels. Any help on this would be greatly appreciated.


回答1:


How about built-in PointToScreen and PointFromScreen methods? Or am I missing something?




回答2:


WpfUnit is coming out as zero because it's doing integer math with the 1/96. Explicitly declare those numbers as floats.



来源:https://stackoverflow.com/questions/1189384/wpf-pixels-to-desktop-pixels

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