package com.excelliance.open.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.util.Log;

import com.excelliance.open.BwbxUI;

public class BitmapUtils {
    private static final String TAG = "BitmapUtils";

    //将图片转化为适应屏幕的Bitmap类型
    public static Bitmap picture(Context context, Bitmap bitmap, int screenWidth, int screenHeight) {
        if (bitmap == null) {
            return null;
        }
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();
        float scaleWidth = ((float) screenWidth) / width;
        float scaleHeight = ((float) screenHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        float rad = Math.max(scaleWidth, scaleHeight);
        int xStart = 0;
        int yStart = 0;
        int sMode = BwbxUI.getGlobalInt(context, "SCALE_MODE_IN_NEXTCHAPTER", 0);
        Log.d(TAG, "sMode :  " + sMode);
        if (sMode == 0) {
            matrix.postScale(rad, rad);
            if (rad == scaleHeight) {
                xStart = (int) ((width - screenWidth / rad) / 2);
                width = (int) (screenWidth / rad);
            } else {
                yStart = (int) ((height - screenHeight / rad) / 2);
                height = (int) (screenHeight / rad);
            }

        } else if (sMode == 1) {
            matrix.postScale(rad, rad);
        } else {
            matrix.postScale(scaleWidth, scaleHeight);
        }
        try {
            // 得到新的图片
            Bitmap newBitmap = Bitmap.createBitmap(bitmap, xStart, yStart, width, height, matrix, true);
            //createBitmap可能会生成和原始图片一样的对象，所以需要判断生成的图片和原始图片不同的时候，再对原始图片进行回收。
            if (bitmap != newBitmap && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
            return newBitmap;
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            return null;
        }
    }

}
