How do I convert a WPF size to physical pixels?

前端 未结 4 1441
灰色年华
灰色年华 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:04

    Simple proportion between Screen.WorkingArea and SystemParameters.WorkArea:

    private double PointsToPixels (double wpfPoints, LengthDirection direction)
    {
        if (direction == LengthDirection.Horizontal)
        {
            return wpfPoints * Screen.PrimaryScreen.WorkingArea.Width / SystemParameters.WorkArea.Width;
        }
        else
        {
            return wpfPoints * Screen.PrimaryScreen.WorkingArea.Height / SystemParameters.WorkArea.Height;
        }
    }
    
    private double PixelsToPoints(int pixels, LengthDirection direction)
    {
        if (direction == LengthDirection.Horizontal)
        {
            return pixels * SystemParameters.WorkArea.Width / Screen.PrimaryScreen.WorkingArea.Width;
        }
        else
        {
            return pixels * SystemParameters.WorkArea.Height / Screen.PrimaryScreen.WorkingArea.Height;
        }
    }
    
    public enum LengthDirection
    {
        Vertical, // |
        Horizontal // ——
    }
    

    This works fine with multiple monitors as well.

提交回复
热议问题