直接上代码: 看注解
@SuppressLint("AppCompatCustomView")
public class MyTestImageView extends ImageView {
private float width;
private float height;
private float radius;
private Paint paint;
private Matrix matrix;
public MyTestImageView(Context context) {
this(context, null);
}
public MyTestImageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
paint.setAntiAlias(true);
matrix = new Matrix();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = getMeasuredWidth();
height = getMeasuredHeight();
radius = DensityUtils.dpForPx(3);
}
@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
// 第三种就直接用 PorterDuffXfermode 去交集 DST_IN 来得倒 交集的后 gif 图片展示
//加这个是为了隔离图层,避免黑色的底边
int layerID = canvas.saveLayer(0, 0, width, height, paint, Canvas.ALL_SAVE_FLAG); @SuppressLint("DrawAllocation") RectF f1 = new RectF(0.0f, 0.0f, width, height);
@SuppressLint("DrawAllocation") Path ra = new Path();
ra.addRoundRect(f1, radius, radius, Path.Direction.CCW);
paint.setColor(ContextCompat.getColor(this.getContext(), R.color.color_fff));
// canvas.clipPath(ra);//第一种 直接裁剪画布,根据实践有锯齿
super.onDraw(canvas);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawPath(ra, paint);
paint.setXfermode(null);
//回复图层
canvas.restoreToCount(layerID);
// 第二种 给imageview 加相框 不过得适配画笔颜色和布局背景颜色一样。
// Drawable drawable = getDrawable();
// if (null != drawable) {
// @SuppressLint("DrawAllocation")
// RectF f = new RectF(0.0f, 0.0f, width, height);
// @SuppressLint("DrawAllocation") Path now = new Path();
// @SuppressLint("DrawAllocation") Path bg = new Path();
// bg.addRect(f, Path.Direction.CCW);
// now.addRoundRect(f, radius, radius, Path.Direction.CCW);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
// now.op(bg, now, Path.Op.DIFFERENCE);
// canvas.drawPath(now, paint);
// }
}
}