在咱们实际的项目开发中,经常会遇到需要把整个View裁剪成圆角的那种。如果用shape来做,那么圆角依旧裁剪不掉。
谷歌出品过一个叫CardView的控件,可以很方便的设置圆角。但是这个在Android 5.0以下不兼容。
最近项目要用到这个,所以我就想起了很早之前我在谷歌的源码里找到过一个比较简单的实现方案,这里贴一下,以后谁搜到我这篇博客可以直接使用了。
代码贴一下,就一个类,很简单。
public class CornerView extends FrameLayout {
public CornerView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CornerView(Context context) {
super(context);
init();
}
private final RectF roundRect = new RectF();
private float rect_adius = 10;
private final Paint maskPaint = new Paint();
private final Paint zonePaint = new Paint();
private void init() {
maskPaint.setAntiAlias(true);
maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
//
zonePaint.setAntiAlias(true);
zonePaint.setColor(Color.WHITE);
//
float density = getResources().getDisplayMetrics().density;
rect_adius = rect_adius * density;
}
public void setCorner(float adius) {
rect_adius = adius;
invalidate();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
int w = getWidth();
int h = getHeight();
roundRect.set(0, 0, w, h);
}
@Override
public void draw(Canvas canvas) {
canvas.saveLayer(roundRect, zonePaint, Canvas.ALL_SAVE_FLAG);
canvas.drawRoundRect(roundRect, rect_adius, rect_adius, zonePaint);
canvas.saveLayer(roundRect, maskPaint, Canvas.ALL_SAVE_FLAG);
super.draw(canvas);
canvas.restore();
}
}
其中,rect_adius是角度,可以外部设置进去。FrameLayout可以换成RelativeLayout,LinearLayout 等。
任何被包裹进去的View都会被裁剪成圆角。
重要提示:得对这个View 设置一个background color 圆角才生效。
2016-11-25补充:经过我们项目测试,这个在ListView、RecyclerView中性能很差,导致滑动不流畅,原因是绘制花费时间。
===============================
如果你觉得帮到了你,请给作者打赏一口饭吃: