Pixel to Centimeter?

前端 未结 9 1590
忘了有多久
忘了有多久 2020-11-29 02:35

I just want to know if the pixel unit is something that doesn\'t change, and if we can convert from pixels to let\'s say centimeters ?

9条回答
  •  [愿得一人]
    2020-11-29 03:03

    The pixel system is that it depend on your screen resolution. Well , first you should get the dpi(density pixel perInch) of your screen. For example your screen dpi is 96;

    1 CM = 37.795276F Pixel in 96dpi.

    37.795276F / 96F = 0.03937007F which is each pixel in 1dpi.

    now you can make it adapted to your screen by getting the current dpi of screen and multiply it to 0.03937007F. then you have each Centimeter in your desire dpi(screen resolution)

    lets set scenario .

    I want to make a methode which get CM and return pixel base on screen Dpi;

    public float CentimeterToPixel(int valueCM, float dpi)
    {
       return 0.03937007F * dpi * valueCM;
    }
    

    if you want to make it more accurate you have to approach dpiX & dpiY.

    for example in C# winforms You can add an object of Graphics from System.Drawing And System.Drawing.Drawing2D then Get it dpiX & dpiY value and design youre area based on it to have more acurate calculation(in some case that horizontal resolution differ from vertical). See the code bellow.

    using System;
    using System.Windows.Forms;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Drawing.Imaging;
    
    namespace MyApp
    {
        static class MyAppClass
        {
            private static Bitmap bmp = new Bitmap(1, 1);// a simple bitmap that automaticaly created base on current screen resolution
            private static Graphics graphic = Graphics.FromImage(bmp);
    
            public static float CentimeterToPixelWidth(int valueCM)
            {
               return 0.03937007F * graphic.DpiX * valueCM;
            }
    
            public static float CentimeterToPixelHeight(int valueCM)
            {
               return 0.03937007F * graphic.DpiY * valueCM;
            }
        }
    
    }
    

    Whish it help you, Heydar.

提交回复
热议问题