android dp转px

2018-05-16  本文已影响0人  小婷婷tt

public static int dip2px(Context context,float dipValue) {

return (int) (dipValue * (getScreenDensity(context) /160f) +0.5f);

}

public static int px2dip(Context context,float pxValue) {

return (int) ((pxValue *160) /getScreenDensity(context));

}

public static float sp2px(Context context,float sp) {

return sp *getScreenScaledDensity(context);

}

public static float px2sp(Context context,float px) {

return px /getScreenScaledDensity(context) +0.5f;

}

@SuppressWarnings("deprecation")

public static int getScreenDensity(Context context) {

DisplayMetrics dm =new DisplayMetrics();

((Activity) context).getWindowManager().getDefaultDisplay()

.getMetrics(dm);

return dm.densityDpi;

}

/**

* get Screen Density

* @param context

* @return

*/

@SuppressWarnings("deprecation")

public static float getScreenScaledDensity(Context context) {

return context.getResources().getDisplayMetrics().scaledDensity;

}

调用举例:ViewUtils.dip2px(mContext,12);

上一篇 下一篇

猜你喜欢

热点阅读