package com.common.lib_base.utils;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.load.resource.bitmap.TransformationUtils;

import java.security.MessageDigest;

import io.reactivex.annotations.NonNull;

/**
 * Date: 2023/2/27 0027 17:04
 * Description:
 */
public class GlideRoundTransform extends BitmapTransformation {
    private static float radius = 0f;

//    static boolean isTopRound = false;

    public GlideRoundTransform() {
        this(4);
    }

    public GlideRoundTransform(int dp) {
        super();
        this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
    }

//    public GlideRoundTransform(int dp, boolean isTopRound) {
//        super();
//        this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
//        this.isTopRound = isTopRound;
//    }


    @Override
    protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
        //变换的时候裁切
        Bitmap bitmap = TransformationUtils.centerCrop(pool, toTransform, outWidth, outHeight);
        return roundCrop(pool, bitmap);
    }

    @Override
    public void updateDiskCacheKey(MessageDigest messageDigest) {

    }


    private static Bitmap roundCrop(BitmapPool pool, Bitmap source) {
        if (source == null) {
            return null;
        }
        Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        }
        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
//        LogUtils.e("GlideRoundTransform--isTopRound:" + isTopRound);
//        if (isTopRound) {
            //左上角、右上角圆角
//            RectF rectRound = new RectF(0f, 100f, source.getWidth(), source.getHeight());
//            canvas.drawRect(rectRound, paint);

//        } else {
            // 都是圆角
            RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
            canvas.drawRoundRect(rectF, radius, radius, paint);
//        }


        return result;
    }
}
