android dp转px

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);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容