1.canvas方法的使用
canvas提供了clipPath,clipRect和clipRegion等方法对控件进行剪裁,通过这些方法的组合可以实现任何形状的控件,当然前提是数学够好的情况下。在本文中使用的是clipPath方法对imageView进行剪裁实现圆角和切去直角两种效果的展示。
2.圆角
2.1实现
自定义控件RoundImageVIew继承ImageView,重写onlayout函数和ondraw函数,具体实现如下所示。根据path路径的不同,可剪裁一个或者多个边角,然后angle的大小即圆的半径。Path路径其实可以看作是一个个点连成的图形,以imageview的左上角为圆点,然后依次设置不同的点,点连接起来形成的图形就是ImageView剪裁后的形状。
int width;
int height;
int angle = 50;
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
width = getWidth();
height = getHeight();
}
@Override
protected void onDraw(Canvas canvas) {
Path path = new Path();
path.moveTo(angle, 0);
path.lineTo(width - angle, 0);
path.quadTo(width, 0, width, angle);//第一个角
path.lineTo(width, height - angle);
path.quadTo(width, height, width - angle, height);//2
path.lineTo(angle, height);
path.quadTo(0, height, 0, height - angle);//3
path.lineTo(0, angle);
path.quadTo(0, 0, angle, 0);//4
canvas.clipPath(path);
super.onDraw(canvas);
}
2.2效果图
3.切去直角
3.1代码
int width;
int height;
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
width = getWidth();
height = getHeight();
}
int length = 50;
@Override
protected void onDraw(Canvas canvas) {
Path path = new Path();
path.moveTo(length, 0);
path.lineTo(width - length, 0);
path.lineTo(width, length);
path.lineTo(width,height-length);
path.lineTo(width-length,height);
path.lineTo(length,height);
path.lineTo(0,height-length);
path.lineTo(0,length);
path.lineTo(length,0);
canvas.clipPath(path);
super.onDraw(canvas);
}
可根据具体需求来设置path路径来实现剪裁不同的图形。