dp与px互转

版权声明:本文为luoyong原创文章,转载请注明出处!https://blog.csdn.net/luoyong_blog https://blog.csdn.net/luoyong_blog/article/details/84253713

这是项目中用到的dp与px互转的工具


import android.content.Context;

/**
 * Created by LY on 2017/3/7.
 * 1.dp转px
 * 2.px转dp
 */
public class DensityUtil {
    public static int dip2px(float dip, Context context) {
        float density = context.getResources().getDisplayMetrics().density;
        int px = (int) (dip * density + 0.5f);// 4.9->4, 4.1->4, 四舍五入
        return px;
    }

    public static float px2dip(int px, Context context) {
        float density = context.getResources().getDisplayMetrics().density;
        float dp = px / density;
        return dp;
    }
}

猜你喜欢

转载自blog.csdn.net/luoyong_blog/article/details/84253713