CommonUtil.java 13.3 KB
package com.prws.common.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.media.ExifInterface;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;

import com.prws.common.bean.CutPicBean;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Random;

/**
 * 获得屏幕相关的辅助类
 */
public class CommonUtil {
    private CommonUtil() {
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    /**
     * sp或者 dp 装换为 px
     */
    public static int dpToPx(Context context, int dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return Math.round(dpValue * scale);
    }

    /**
     * 获得屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 获得状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusHeight(Context context) {

        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

    /**
     * 获取当前屏幕截图,包含状态栏
     *
     * @param activity
     * @return
     */
    public static Bitmap snapShotWithStatusBar(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        int width = getScreenWidth(activity);
        int height = getScreenHeight(activity);
        Bitmap bp = null;
        bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
        view.destroyDrawingCache();
        return bp;

    }

    /**
     * 获取当前屏幕截图,不包含状状态栏
     *
     * @param activity
     * @return
     */
    public static Bitmap snapShotWithoutStatusBar(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;

        int width = getScreenWidth(activity);
        int height = getScreenHeight(activity);
        Bitmap bp = null;
        bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
                - statusBarHeight);
        view.destroyDrawingCache();
        return bp;
    }

    public static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;
        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pi;
    }

    //相乘
    public static double mul(double a1, double b1) {
        BigDecimal a2 = new BigDecimal(Double.toString(a1));
        BigDecimal b2 = new BigDecimal(Double.toString(b1));
        return a2.multiply(b2).doubleValue();
    }

    //相乘
    public static int mulForInt(double a1, double b1) {
        BigDecimal a2 = new BigDecimal(Double.toString(a1));
        BigDecimal b2 = new BigDecimal(Double.toString(b1));
        return a2.multiply(b2).intValue();
    }

    //相除
    public static double div(double a1, double b1, int scale) {
        //scale参数为除不尽时,指定精度。
        if (scale < 0) {
            throw new IllegalArgumentException("error");
        }
        BigDecimal a2 = new BigDecimal(Double.toString(a1));
        BigDecimal b2 = new BigDecimal(Double.toString(b1));
        return a2.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    //相除
    public static int divForInt(double a1, double b1, int scale) {
        //scale参数为除不尽时,指定精度。
        if (scale < 0) {
            throw new IllegalArgumentException("error");
        }
        BigDecimal a2 = new BigDecimal(Double.toString(a1));
        BigDecimal b2 = new BigDecimal(Double.toString(b1));
        return a2.divide(b2, scale, BigDecimal.ROUND_HALF_UP).intValue();
    }

    public static String getStr() {
        String str = new String();
        Random r = new Random();

        for (int i = 0; i < 5; i++) {

            int temp = r.nextInt(58) + 65;
            // 随机生成 65—122 的数(A—z)

            if ((temp >= 'A' && temp <= 'Z') || (temp >= 'a' && temp <= 'z')) {
                // 判断随机数是不是(A-Z)||(a-z)

                str += (char) temp;
                // 将当前随机数强制转化为字符类型并和字符串相加

            } else {
                // 不满足条件,将当前的i再执行一次
                i--;
            }
        }
        return str;
        // 返回长度为5的随机字符串,字符串由随机的5个大小写字母组成
    }

    /**
     * @param bmp
     * @param uri
     * @return 保存bitmap到指定路径
     */
    public static boolean saveBitmapToUri(Bitmap bmp, String uri) {
        final File imgFile = new File(uri);
        if (!imgFile.exists()) {
            imgFile.getParentFile().mkdir();
        }

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(imgFile);
            bmp.compress(Bitmap.CompressFormat.JPEG, 85, fos);
            fos.flush();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static String formatTime(Long time) {
        Long seconds = time / 1000;
        String standardTime;
        if (seconds <= 0) {
            standardTime = "00:00";
        } else if (seconds < 60) {
            standardTime = String.format(Locale.getDefault(), "00:%02d", seconds % 60);
        } else if (seconds < 3600) {
            standardTime = String.format(Locale.getDefault(), "%02d:%02d", seconds / 60, seconds % 60);
        } else {
            standardTime = String.format(Locale.getDefault(), "%02d:%02d:%02d", seconds / 3600, seconds % 3600 / 60, seconds % 60);
        }
        return standardTime;
    }

    public static String formatTimeChinese(Long time) {
        Long seconds = time / 1000;
        String standardTime;
        if (seconds <= 0) {
            standardTime = "00:00";
        } else if (seconds < 60) {
            standardTime = String.format(Locale.getDefault(), "%02d秒", seconds % 60);
        } else if (seconds < 3600) {
            standardTime = String.format(Locale.getDefault(), "%02d分%02d秒", seconds / 60, seconds % 60);
        } else {
            standardTime = String.format(Locale.getDefault(), "%02d时%02d分%02d秒", seconds / 3600, seconds % 3600 / 60, seconds % 60);
        }
        return standardTime;
    }

    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        //旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 创建新的图片
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    public static List<String> getYears(int num) {
        List<String> list = new ArrayList<>();
        list.add("全部");
        Calendar cd = Calendar.getInstance();
        int year = cd.get(Calendar.YEAR);
        for (int i = 0; i < num; i++) {
            list.add(Integer.toString(year));
            year--;
        }
        return list;
    }

    public static int[] getRawScreenSize(Context context) {
        int[] size = new int[2];

        WindowManager w = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display d = w.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        d.getMetrics(metrics);
        // since SDK_INT = 1;
        int widthPixels = metrics.widthPixels;
        int heightPixels = metrics.heightPixels;

        // includes window decorations (statusbar bar/menu bar)
        if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
            try {
                widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
                heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
            } catch (Exception ignored) {
            }
        // includes window decorations (statusbar bar/menu bar)
        if (Build.VERSION.SDK_INT >= 17)
            try {
                Point realSize = new Point();
                Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
                widthPixels = realSize.x;
                heightPixels = realSize.y;
            } catch (Exception ignored) {
            }
        size[0] = widthPixels;
        size[1] = heightPixels;
        return size;
    }

    public static List<Rect> getRect(List<CutPicBean.FigLoaction> list, Bitmap bitmap, int height, int width) {
        List<Rect> rects = new ArrayList<>();
        for (CutPicBean.FigLoaction figLoaction : list) {
            Rect rect = new Rect();
            rect.left = figLoaction.getPoints().get(0).getX() * width / bitmap.getWidth();
            rect.top = figLoaction.getPoints().get(0).getY() * height / bitmap.getHeight();
            rect.right = figLoaction.getPoints().get(2).getX() * width / bitmap.getWidth();
            rect.bottom = figLoaction.getPoints().get(2).getY() * height / bitmap.getHeight();
            rects.add(rect);
        }
        return rects;
    }

    public static Rect getRect(CutPicBean.FigLoaction figLoaction, Bitmap bitmap, int height, int width) {
        Rect rect = new Rect();
        rect.left = figLoaction.getPoints().get(0).getX() * width / bitmap.getWidth();
        rect.top = figLoaction.getPoints().get(0).getY() * height / bitmap.getHeight();
        rect.right = figLoaction.getPoints().get(2).getX() * width / bitmap.getWidth();
        rect.bottom = figLoaction.getPoints().get(2).getY() * height / bitmap.getHeight();
        return rect;
    }

    public static List<CutPicBean.FigLoaction> rotaingLocation(int angle, List<CutPicBean.FigLoaction> list, int width, int height) {
        for (CutPicBean.FigLoaction figLoaction : list) {
            for (CutPicBean.Points points : figLoaction.getPoints()) {
                int x = points.getX();
                int y = points.getY();
                if (angle == 90) {
                    points.setX(height - y);
                    points.setY(x);
                } else if (angle == 180) {
                    points.setX(width - x);
                    points.setY(height - y);
                } else if (angle == 270) {
                    points.setX(y);
                    points.setY(width - x);
                }
            }
        }
        return list;
    }

}