Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Pixels to CM in WPF

Tags:

.net

wpf

I have

?(New System.Windows.LengthConverter()).ConvertFrom("1cm")
37.795275590551178 {Double}
    Double: 37.795275590551178

So, in 1cm I have 37.795275590551178px WPF pixels.

My problem is how I convert back from px to cm?

like image 946
serhio Avatar asked Nov 29 '22 09:11

serhio


1 Answers

As in WPF we deal with DeviceIndependentUnits (DIU, named, conventionally "px"), that units does not depend of the device or screen resolution.

Actually the factors used in .NET Framework (4), for 'px', 'in', 'cm' and 'pt' respectively

// System.Windows.LengthConverter
private static double[] PixelUnitFactors = new double[]
{
    1.0,
    96.0,
    37.795275590551178,
    1.3333333333333333
};

So, we have

private struct PixelUnitFactor
{
    public const double Px = 1.0;
    public const double Inch = 96.0;
    public const double Cm = 37.7952755905512;
    public const double Pt = 1.33333333333333;
}    

public double CmToPx(double cm)
{
    return cm * PixelUnitFactor.Cm;
}

public double PxToCm(double px)
{
    return px / PixelUnitFactor.Cm;
}
like image 116
serhio Avatar answered Dec 09 '22 00:12

serhio