android dp,sp,px conversion tool class, ready to use (including measuring screen width and height)

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.WindowManager;

/**
 * Created by LZC on 2018/1/9.
 */
public class DensityUtil {
    private static int screenWidth = 0;
    private static int screenHeight = 0;
    private static  float density = 0;


    /**
      * Convert from dp unit to px (pixel) according to the resolution of the phone
      */
 public static int dip2px(Context context, float dpValue) {
         final float scale = context.getResources().getDisplayMetrics(). density ;
         return ( int ) (dpValue * scale + 0.5f );    
    }

    public static int sp2px(Context context, float spValue) {
        float scale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int)(spValue * scale + 0.5F);
    }

    public static int px2sp(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int)(pxValue / scale + 0.5F);
    }
    /**
      * Convert from px (pixel) unit to dp according to the resolution of the phone
      */
 public static int px2dip(Context context, float pxValue) {
         final float scale = context.getResources().getDisplayMetrics(). density ;
         return ( int ) (pxValue / scale + 0.5f );    
    }

    public static int getWindowWidth(Context context) {
        if (screenWidth != 0) return screenWidth;
        initWidHeight(context);
        return screenWidth;
    }

    public static int getWindowHeight(Context context) {
        if (screenHeight != 0) return screenHeight;
        initWidHeight(context);
        return screenHeight;
    }

    private static void initWidHeight(Context context) {
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        //获取屏幕信息
        manager.getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
        density  = dm.density;
    }

    public static float getDensity(Context context){
        if (density != 0) return density;
        initWidHeight(context);
        return  density;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324854815&siteId=291194637