项目开发中遇到联系头像需要设置成圆角或者圆形图片
技术实现,自定义继承自ImageView 的子类,Override Ondraw
private Path clipPath =new Path();
// 圆角图
protected void onDraw(Canvas canvas) {
clipPath.addRoundRect(new RectF(0, 0, getWidth(), getHeight()), 10.0f, 10.0f, Path.Direction.CW);
canvas.clipPath(clipPath);
super.onDraw(canvas);
}
其中10.0f 为圆角半径
如果是一张正方形的图片设置其值为getWidth()/2 实现效果是可以实现一个圆形图片效果的
// 圆形图
protected void onDraw(Canvas canvas) {
clipPath.addCircle(getWidth()/2,getHeight()/2,getWidth()/2,Path.Direction.CCW);
//clipPath.addRoundRect(new RectF(0, 0, getWidth(), getHeight()), 10.0f, 10.0f, Path.Direction.CW);
canvas.clipPath(clipPath);
super.onDraw(canvas);
}
也就是说在正方形图的基础上:
clipPath.addCircle(getWidth()/2,getHeight()/2,getWidth()/2,Path.Direction.CCW);
与
clipPath.addRoundRect(new RectF(0, 0, getWidth(), getHeight()), getWidth()/2, getHeitght()/2, Path.Direction.CW);
达到的效果一致,都可以实现一个圆图,
但是这样实现的圆图是有毛边的,
要继续优化界面,办法是有的:Canvas 在上面圆图的基础上再画一个圆边
//是Paint.Style.STROKE 不是FILL 不然就覆盖成一块饼了
private final Paint mButtonPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mButtonPaint.setStyle(Paint.Style.STROKE);
mButtonPaint.setColor(mColor);
// 圆形图
protected void onDraw(Canvas canvas) {
clipPath.addCircle(getWidth()/2,getHeight()/2,getWidth()/2,Path.Direction.CCW);
//clipPath.addRoundRect(new RectF(0, 0, getWidth(), getHeight()), 10.0f, 10.0f, Path.Direction.CW);
canvas.clipPath(clipPath);
super.onDraw(canvas);
canvas.drawCircle(getWidth() / 2, getHeight() / 2, (float) (getWidth() / 2), mButtonPaint);
}
效果图: