android px 到 dp的互相转换.

访问量: 223

参考: http://stackoverflow.com/questions/4605527/converting-pixels-to-dp

java代码:

package topgroup.com.topgroupandroid;

import android.content.Context;
import android.content.res.Resources;
import android.util.DisplayMetrics;

/**
 * Created by siwei on 17-3-19.
 * ´Resources.getSystem().getDisplayMetrics()´ if you don't have a Context handy.
 */
public class Tool {

    public static int convertDpToPx(float dp){
        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();

        float px = dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
        return Math.round(px);
    }

    public static int convertPxToDp(float px){

        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        float dp = px / ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
        return Math.round(dp);
    }
}

订阅/RSS Feed

Subscribe

分类/category