Converting pixels to dpi for mdpi and hdpi screens

时间秒杀一切 提交于 2019-12-13 04:17:18

问题


I am using this code that I have found on another thread which is working fine on mdpi screens:

public static float convertDpToPixel(float dp,Context context){
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        float px = dp * (metrics.densityDpi/160f);
        return px;
    }

public static float convertPixelsToDp(float px,Context context){
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        float dp = px / (metrics.densityDpi /160f);
        return dp;

    }

When using it on hdpi screens the text size jumps when trying to increase the text size. I am assuming its because it is using the hardcoded 160f when dividing the densityDpi? Is there any dynamic way to determine whether it is 160dpi or 240dpi?


回答1:


Try this method:

public float dpToPx(float dp, Context context) {
    float density = context.getResources().getDisplayMetrics().density;
    return dp * density;
}



回答2:


From the doc:

metrics.density 

is the scaling factor you are looking for.

This is a scaling factor for the Density Independent Pixel unit, where one DIP is one pixel on an approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen), providing the baseline of the system's display. Thus on a 160dpi screen this density value will be 1; on a 120 dpi screen it would be .75; etc.



来源:https://stackoverflow.com/questions/13751080/converting-pixels-to-dpi-for-mdpi-and-hdpi-screens

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