public class RooundImageView extends android.support.v7.widget.AppCompatImageView {
private Paint paint;
private int radius = 5;
private Paint paint2;
public RooundImageView(Context context) {
this(context, null);
}
public RooundImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RooundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
paint2 = new Paint();
paint2.setXfermode(null);
}
/**
* 设置弧度值
* @param radius
*/
public void setRadius(float radius) {
this.radius = (int) radius;
}
@Override
public void draw(Canvas canvas) {
Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas2 = new Canvas(bitmap);
super.draw(canvas2);
drawLeftUp(canvas2);
drawLeftDown(canvas2);
drawRightDown(canvas2);
drawRightUp(canvas2);
canvas.drawBitmap(bitmap, 0, 0, paint2);
bitmap.recycle();
}
/**
* 左上角的弧度
* @param canvas
*/
private void drawLeftUp(Canvas canvas) {
Path path = new Path();
path.moveTo(0, radius);
path.lineTo(0, 0);
path.lineTo(radius, 0);
path.arcTo(new RectF(0, 0, radius * 2, radius * 2), -90, -90);
path.close();
canvas.drawPath(path, paint);
}
/**
* 左下角的弧度
* @param canvas
*/
private void drawLeftDown(Canvas canvas) {
Path path = new Path();
path.moveTo(0, getHeight() - radius);
path.lineTo(0, getHeight());
path.lineTo(radius, getHeight());
path.arcTo(new RectF(0, getHeight() - radius * 2, radius * 2, getHeight()), 90, 90);
path.close();
canvas.drawPath(path, paint);
}
/**
* 右下角的弧度
* @param canvas
*/
private void drawRightDown(Canvas canvas) {
Path path = new Path();
path.moveTo(getWidth() - radius, getHeight());
path.lineTo(getWidth(), getHeight());
path.lineTo(getWidth(), getHeight() - radius);
path.arcTo(new RectF(getWidth() - radius * 2, getHeight() - radius * 2, getWidth(), getHeight()), 0,
90);
path.close();
canvas.drawPath(path, paint);
}
/**
* 右上角的弧度
* @param canvas
*/
private void drawRightUp(Canvas canvas) {
Path path = new Path();
path.moveTo(getWidth(), radius);
path.lineTo(getWidth(), 0);
path.lineTo(getWidth() - radius, 0);
path.arcTo(new RectF(getWidth() - radius * 2, 0, getWidth(), 0 + radius * 2), -90, 90);
path.close();
canvas.drawPath(path, paint);
}
}
利用path的 arcTo 方法简单实现圆角ImageView。
setRadius设置圆角弧度