package com.miya.print.utils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;

/**
 * bitmap处理工具类
 */
public class BitmapUtils {

    /**
     * 按指定宽高缩放源bitmap
     *
     * @param origin 源bitmap
     * @param width  指定宽度，传0代表按height的比例进行缩放，比例计算公式：scale = origin.getHeight()/height
     * @param height 指定高度，传0代表按width的比例进行缩放，比例计算公式：scale = origin.getWidth()/width
     * @return width，height都传0代表不缩放，外部调用者注意bitmap回收
     */
    public static Bitmap scaleBitmap(Bitmap origin, int width, int height) {
        if (origin == null) {
            return null;
        }
        int widthOrigin = origin.getWidth();
        int heightOrigin = origin.getHeight();
        Matrix matrix = new Matrix();
        float scaleX = (float) width / (float) widthOrigin;
        float scaleY = (float) height / (float) heightOrigin;
        if (width == 0) {
            scaleX = scaleY;
        }
        if (height == 0) {
            scaleY = scaleX;
        }
        if ((width == 0 && height == 0) || width < 0 || height < 0) {
            //返回原图片
            return origin;
        }
        matrix.preScale(scaleX, scaleY);
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, widthOrigin, heightOrigin, matrix, false);
//        if (newBM.equals(origin)) {
//            return newBM;
//        }
//        origin.recycle();
        return newBM;
    }

    /**
     * 给源bitmap添加白色左边距，用于打印对齐
     *
     * @param origin 源bitmap
     * @param width  指定左边距宽度
     * @return
     */
    public static Bitmap addWhiteLeftMargin(Bitmap origin, int width) {
        if (origin == null) {
            return null;
        }
        if (width <= 0) {
            return origin;
        }
        Bitmap newBm = Bitmap.createBitmap(width + origin.getWidth(), origin.getHeight(), origin.getConfig());
        Canvas canvas = new Canvas(newBm);
        //绘制左边白色边距
        canvas.drawColor(0xffffffff);
        canvas.drawBitmap(origin, width, 0, null);
        return newBm;
    }
}
