前言
实现圆角或圆形图片显示,我们开发中除了把原图直接做成圆角外,常见有三种方式实现:
使用Xfermode混合图层;
使用BitmapShader;
通过裁剪画布区域实现指定形状的图形(ClipPath)。
今天我就来带大家通过上面三种方式实现圆角或圆形的自定义View。
先来张效果图:
实现
1. 自定义属性
<attr name="borderRadius" format="dimension" />
<attr name="type">
<enum name="circle" value="0" />
<enum name="round" value="1" />
</attr>
<attr name="src" format="reference"/>
<declare-styleable name="XfermodeCircleView">
<attr name="borderRadius" />
<attr name="type" />
<attr name="src" />
</declare-styleable>
属性说明:
type: 圆角或圆形
src: 图片资源Id(这里使用的资源图片作为案例)
borderRadius: 圆角半径大小
2. 自定义View
我这里自定义了三个View, 大部分代码一致的,就是在onDraw方法实现不一样, 所以我这里就不重复贴出来了。
XfermodeCircleView、ClipPathCircleView 继承的View
BitmapShaderView 继承的ImageView
属性
private static final int TYPE_CIRCLE = 0;
private static final int TYPE_ROUND = 1;
private int mRadius; //半径大小
private int mBorderRadius; //圆角大小
private int mWidth, mHeight; //控件宽高
private int mType; //圆角还是圆
private RectF mRoundRect; // 圆角矩阵
private BitmapShader mBitmapShader; //Shader
private Paint mBitmapPaint; //图片画笔
private Matrix mMatrix; //Bitmap缩放矩阵
构造函数
public XfermodeCircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.XfermodeCircleView, defStyleAttr, 0);
this.mSrc = BitmapFactory.decodeResource(getResources(), a.getResourceId(R.styleable.XfermodeCircleView_src, 0));
this.mType = a.getInt(R.styleable.XfermodeCircleView_type, 0);
this.mBorderRadius = a.getDimensionPixelSize(R.styleable.XfermodeCircleView_borderRadius, 10);
a.recycle();
init();
}