在 Android-实现图片圆角显示的几种方式 我分享了一个不到100行代码实现的圆角ImageView,后面根据需求增加了,边框和自定义Path。这篇文章就是来分享具体是怎样实现的。
先放一张动图,应该就能明白其中的原理了。
以圆形为例:
- 首先绘制一张全尺寸矩形,颜色为边框的颜色;
- 再画一个小一点的圆形,把第一步的图层掏空,这个圆形小多少就是边框的宽度;
- 最后画一个正常大小的圆形,把多余的都扣掉。
扣图都是使用的 Xfermodes 具体到
- 步骤2,PorterDuff.Mode.DST_OUT:去交集,显示下层
- 步骤3,PorterDuff.Mode.DST_IN:取交集,显示下层。
核心代码:
mStrokePaint.setXfermode(null);
canvas.drawBitmap(mStrokeBitmap, 0, 0, mStrokePaint);
canvas.translate(mStrokeWidth, mStrokeWidth);
mStrokePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
mStrokeShape.draw(canvas, mStrokePaint);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
mShape.draw(canvas, mPaint);
自定义Path
这个功能是源于公司项目需要,基于这个可以实现很多意想不到的效果,如下图
原理还是 Xfermodes 的扣图功能,区别就是把接口暴露出来,就可以自定义啦。
使用
广告时间到啦,这么好的库要怎么使用呢?
compile 'cn.gavinliu.android.lib:ShapedImageView:0.8.2
Circle
Round Rect
PathExtension
image1.setExtension(new CDPathExtension());
class CDPathExtension implements ShapedImageView.PathExtension {
@Override
public void onLayout(Path path, int width, int height) {
path.reset();
path.addCircle(width / 2, height / 2, width / 8, Path.Direction.CW);
}
}