1.如果大家不熟悉圆形或者path的以及canvas.clipPath,可以参考我的一篇文章:圆形头像
2.今天我们依旧通过Canvas的画布剪切来完成,有所不同的是,这次的path不是一个圆,而是在矩形中画圆addRoundRect
- public class MyRoundJiaoImageView extends AppCompatImageView {
-
- private int leftTopRadius;
- private int rightTopRadius;
- private int leftBottomRadius;
- private int rightBottomRadius;
- private int allRadius;
-
- public MyRoundJiaoImageView(Context context) {
- super(context);
- }
-
- public MyRoundJiaoImageView(Context context, AttributeSet attrs) {
- super(context, attrs);
- initAtter(context, attrs);
- }
-
- private void initAtter(Context context, AttributeSet attrs) {
- TypedArray typed = context.obtainStyledAttributes(attrs, R.styleable.roundRadion);
-
- if (typed == null)
- return;
-
-
- leftTopRadius = typed.getInt(R.styleable.roundRadion_mleftTopRadius, 0);
- rightTopRadius = typed.getInt(R.styleable.roundRadion_mrightRadius, 0);
- leftBottomRadius = typed.getInt(R.styleable.roundRadion_mleftButtomRadius, 0);
- rightBottomRadius = typed.getInt(R.styleable.roundRadion_mrightButtomRadius, 0);
- allRadius = typed.getInt(R.styleable.roundRadion_allRadius, 0);
-
-
- typed.recycle();
- }
-
-
- @Override
- protected void onDraw(Canvas canvas) {
-
- int width = getMeasuredWidth();
- int height = getMeasuredHeight();
- Path path = new Path();
- /*向路径中添加圆角矩形。radii数组定义圆角矩形的四个圆角的x,y半径。radii长度必须为8*/
-
- if (allRadius > 0) {
- float rids[] = {allRadius, allRadius, allRadius, allRadius, allRadius, allRadius, allRadius, allRadius};
- path.addRoundRect(new RectF(0, 0, width, height), rids, Path.Direction.CW);
-
- } else {
- float rids[] = {leftTopRadius, leftTopRadius, rightTopRadius, rightTopRadius, leftBottomRadius, leftBottomRadius, rightBottomRadius, rightBottomRadius};
- path.addRoundRect(new RectF(0, 0, width, height), rids, Path.Direction.CW);
- }
-
-
- canvas.clipPath(path);
-
- super.onDraw(canvas);
- }
-
- public void setAllRadius(int allRadius) {
- this.allRadius = allRadius;
- invalidate();
- }
- }
如果对画布的操作,需要在onDraw的super之前完成,否则将不会生效
参数如下:
- <declare-styleable name="roundRadion">
-
- <attr name="mleftTopRadius" format="integer" />
- <attr name="mrightRadius" format="integer" />
- <attr name="mleftButtomRadius" format="integer" />
- <attr name="mrightButtomRadius" format="integer" />
- <attr name="allRadius" format="integer" />
-
- declare-styleable>
public void addRoundRect(RectF rect, float[] radii, Direction dir)
RectF :矩形的范围
radii:四个角的角度参数,正常需要8个值,因为我们知道一个角确定下来需要两个角度的坐标
- float rids[] = {leftTopRadius, leftTopRadius, rightTopRadius, rightTopRadius, leftBottomRadius, leftBottomRadius, rightBottomRadius, rightBottomRadius};
-
-
-
- A.(leftTopRadius, leftTopRadius)
-
- B(rightTopRadius, rightTopRadius)
-
- C(leftBottomRadius, leftBottomRadius)
-
- D(rightBottomRadius, rightBottomRadius)
坐标里面的值需一样,否则开角不同,会导致不生效
Direction :绘制的方向
3.只要我们path路径准备好,canvs绘制路径即可。