Android手機屏幕px轉dp和dp轉px工具類

jopen 9年前發布 | 1K 次閱讀 Java Android

import android.content.Context;

public class DensityUtil {

private static float scale;

/**
 * 根據手機的分辨率從 dp 的單位 轉成為 px(像素)
 */
public static int dip2px(Context context, float dpValue) {
    if (scale == 0) {
        scale = context.getResources().getDisplayMetrics().density;
    }
    return (int) (dpValue * scale + 0.5f);
}

/**
 * 根據手機的分辨率從 px(像素) 的單位 轉成為 dp
 */
public static int px2dip(Context context, float pxValue) {
    if (scale == 0) {
        scale = context.getResources().getDisplayMetrics().density;
    }
    return (int) (pxValue / scale + 0.5f);
}

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!