Android-自定义圆角ImageView

继承ImageView,重写onDraw方法,获取长跟宽之后使用clip方法裁剪圆角,之后调用super的onDraw。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class KJCornerImageView extends android.support.v7.widget.AppCompatImageView{
private float[] radiusArray = { 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f };

public KJCornerImageView(Context context) {
this(context,null);
}

public KJCornerImageView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}

public KJCornerImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.KJCornerImageView);
int leftBottom = typedArray.getDimensionPixelSize(R.styleable.KJCornerImageView_leftBottomCorner, 0);
int leftTop = typedArray.getDimensionPixelSize(R.styleable.KJCornerImageView_leftTopCorner, 0);
int rightBottom = typedArray.getDimensionPixelSize(R.styleable.KJCornerImageView_rightBottomCorner, 0);
int rightTop = typedArray.getDimensionPixelSize(R.styleable.KJCornerImageView_rightTopCorner, 0);
radiusArray[1] = leftTop;
radiusArray[2] = rightTop;
radiusArray[3] = rightTop;
radiusArray[4] = rightBottom;
radiusArray[5] = rightBottom;
radiusArray[6] = leftBottom;
radiusArray[7] = leftBottom;
typedArray.recycle();
}

public void setRadius(float leftTop, float rightTop, float rightBottom, float leftBottom) {
radiusArray[0] = leftTop;
radiusArray[1] = leftTop;
radiusArray[2] = rightTop;
radiusArray[3] = rightTop;
radiusArray[4] = rightBottom;
radiusArray[5] = rightBottom;
radiusArray[6] = leftBottom;
radiusArray[7] = leftBottom;

invalidate();
}

protected void onDraw(Canvas canvas) {
Path path = new Path();
path.addRoundRect(new RectF(0, 0, getWidth(), getHeight()), radiusArray, Path.Direction.CW);
canvas.clipPath(path);
super.onDraw(canvas);
}
}