前言
之前介绍过对ImageView进行圆角处理,具体文章《Android中ImageView半边圆角处理记录 -笔友城堡 – 阅读是一种生活方式 ()》,后面发现网上还有一种更简单的一种方式。
- 有点:代码少,简单
- 缺点:边界不够圆滑(存在锯齿)
正文
具体效果如下(左侧是RoundImageView2,右侧是之前RoundImageView),看圆角处,RoundImageView2就存在锯齿。
代码片段
public class RoundImageView2 extends androidx.appcompat.widget.AppCompatImageView {
private final Path mPath;
private float mWidth, mHeight;
public RoundImageView2(Context context) {
this(context, null);
}
public RoundImageView2(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundImageView2(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mPath = new Path();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
mWidth = getWidth();
mHeight = getHeight();
}
@Override
protected void onDraw(Canvas canvas) {
int radius = 20; //圆角半径
if (mWidth > radius && mHeight > radius) {
mPath.moveTo(radius, 0);
mPath.lineTo(mWidth - radius, 0);
mPath.quadTo(mWidth, 0, mWidth, radius);
mPath.lineTo(mWidth, mHeight - radius);
mPath.quadTo(mWidth, mHeight, mWidth - radius, mHeight);
mPath.lineTo(radius, mHeight);
mPath.quadTo(0, mHeight, 0, mHeight - radius);
mPath.lineTo(0, radius);
mPath.quadTo(0, 0, radius, 0);
canvas.clipPath(mPath);
}
super.onDraw(canvas);
}
}
参考文章
© 版权声明