import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.NonNull;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
/**
* @author Relin
* @date 2019-10-18 10:18:20
* 圆角转化工具类<br/>
* 支持4个角自定义,同时支持4个角同时定义。<br/>
*/
public class RadiusTransform extends BitmapTransformation {
private static final String ID = RadiusTransform.class.getPackage().getName() + RadiusTransform.class.getName();
private static final byte[] ID_BYTES = ID.getBytes(CHARSET);
/**
* 左上圆角
*/
private int topLeftRadius;
/**
* 右上圆角
*/
private int topRightRadius;
/**
* 下左圆角
*/
private int bottomLeftRadius;
/**
* 下右圆角
*/
private int bottomRightRadius;
/**
* 设置4角圆角大小
*
* @param radius 圆角大小
*/
public RadiusTransform(int radius) {
this.topLeftRadius = radius;
this.topRightRadius = radius;
this.bottomLeftRadius = radius;
this.bottomRightRadius = radius;
}
/**
* 分别设置4个角的圆角大小
*
* @param topLeftRadius 左上圆角
* @param topRightRadius 右上圆角
* @param bottomLeftRadius 下左圆角
* @param bottomRightRadius 下右圆角
*/
public RadiusTransform(int topLeftRadius, int topRightRadius, int bottomLeftRadius, int bottomRightRadius) {
this.topLeftRadius = topLeftRadius;
this.topRightRadius = topRightRadius;
this.bottomLeftRadius = bottomLeftRadius;
this.bottomRightRadius = bottomRightRadius;
}
@Override
protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
int width = toTransform.getWidth();
int height = toTransform.getHeight();
Bitmap bitmap = pool.get(width, height, Bitmap.Config.ARGB_8888);
bitmap.setHasAlpha(true);
bitmap.setDensity(toTransform.getDensity());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new BitmapShader(toTransform, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
//左上
canvas.drawRoundRect(new RectF(0, 0, width / 2, height / 2), topLeftRadius, topLeftRadius, paint);
//右上
canvas.drawRoundRect(new RectF(width / 2, 0, width, height / 2), topRightRadius, topRightRadius, paint);
//下左
canvas.drawRoundRect(new RectF(0, height / 2, height / 2, height), bottomLeftRadius, bottomLeftRadius, paint);
//下右边
canvas.drawRoundRect(new RectF(width / 2, height / 2, width, height), bottomRightRadius, bottomRightRadius, paint);
//填充空白
canvas.drawRect(new Rect(width / 4, 0, width * 3 / 4, height), paint);
canvas.drawRect(new Rect(0, height / 4, width, height * 3 / 4), paint);
return bitmap;
}
@Override
public void updateDiskCacheKey(MessageDigest messageDigest) {
messageDigest.update(ID_BYTES);
}
}
Android Glide RadiusTransform
最新推荐文章于 2024-08-09 07:22:44 发布