《Android 屏幕单位转换工具类》

百里光熙
2023-12-01

 

/**
 * Created by laizhen on 2017/6/22.
 * <p>
 * Android屏幕单位转换工具类
 * <p>dp/dip转成为px {@link #dip2px(Context, float)}</p>
 * <p>px转成为dp/dip {@link #px2dip(Context, float)}</p>
 * <p>sp转成为px {@link #sp2px(Context, float)}</p>
 * <p>px转成为sp {@link #px2sp(Context, float)}</p>
 *
 * @author John
 * @version 1.0
 * @date on 2017-5/8/2017 8:49 AM
 */

/**
 * Android屏幕单位转换工具类
 * <p>dp/dip转成为px {@link #dip2px(Context, float)}</p>
 * <p>px转成为dp/dip {@link #px2dip(Context, float)}</p>
 * <p>sp转成为px {@link #sp2px(Context, float)}</p>
 * <p>px转成为sp {@link #px2sp(Context, float)}</p>
 *
 * @author John
 * @version 1.0
 * @date on 2017-5/8/2017 8:49 AM
 */

public class DensityUtils {

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 sp
     */
    public static int sp2px(Context context, float spValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 sp
     */
    public static int px2sp(Context context, float pxValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }
}

 

 类似资料: