Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 圖片單位轉換:px 與 dp 的互轉工具類

編輯:關於 Android 程式設計

以下是一個實用的螢幕單位轉換工具類,用於在 px、dp、sp 之間進行轉換:

package com.lengxiaocai.myutil.screentool;

import android.content.Context;

/**
 * 螢幕像素檢測工具
 */
public class ScreenTool {
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int px2sp(float pxValue, float fontScale) {
        return (int) (pxValue / fontScale + 0.5f);
    }

    public static int sp2px(float spValue, float fontScale) {
        return (int) (spValue * fontScale + 0.5f);
    }
}

核心原理是透過 DisplayMetrics.density 取得螢幕密度縮放因子,dp 轉 px 時乘以 density,px 轉 dp 時除以 density,並用 +0.5f 做四捨五入處理;sp 的轉換則使用 fontScale 字型縮放因子。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved