Learn about screen px and dp systems

Several common conversions

ldpi      320*240   1dp=0.75px 

mdpi    480*320   1dp=1.0px 

hdpi     800*480   1dp=1.5px 

xhdpi   1280*720   1dp=2.0px 

xxhdpi 1920*1080   1dp=3px 


Provide a tool class: dp and px value conversion

public class DensityUtil {

    /**
     * Convert from dp unit to px (pixel) according to the resolution of the phone
     */
    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * Convert from px (pixel) unit to dp according to the resolution of the phone
     */
    public static int px2dp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}

Get the current device screen pixels:

DisplayMetrics dm = getResources().getDisplayMetrics();
        WIDTH = dm.widthPixels;
        HEIGHT = dm.heightPixels;


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325771199&siteId=291194637