How do I convert a WPF size to physical pixels?

前端 未结 4 1432
灰色年华
灰色年华 2020-11-28 21:21

What\'s the best way to convert a WPF (resolution-independent) width and height to physical screen pixels?

I\'m showing WPF content in a WinForms Form (via ElementHo

4条回答
  •  [愿得一人]
    2020-11-28 22:13

    I found a way to do it, but I don't like it much:

    using (var graphics = Graphics.FromHwnd(IntPtr.Zero))
    {
        var pixelWidth = (int) (element.DesiredSize.Width * graphics.DpiX / 96.0);
        var pixelHeight = (int) (element.DesiredSize.Height * graphics.DpiY / 96.0);
        // ...
    }
    

    I don't like it because (a) it requires a reference to System.Drawing, rather than using WPF APIs; and (b) I have to do the math myself, which means I'm duplicating WPF's implementation details. In .NET 3.5, I have to truncate the result of the calculation to match what ElementHost does with AutoSize=true, but I don't know whether this will still be accurate in future versions of .NET.

    This does seem to work, so I'm posting it in case it helps others. But if anyone has a better answer, please, post away.

提交回复
热议问题