CircleImageView实现带边框圆形头像
项目下载地址:https://github.com/hdodenhof/CircleImageView
项目里主要实现了一个自定义控件:CircleImageView
主要理解两个函数:onDraw,setup和updateShaderMatrix
先看个简单的onDraw函数,先画带位图的圆,如果边框的宽度不为0,画一个空心圆
@Override
protected void onDraw(Canvas canvas) {
if (getDrawable() == null) {
return;
}
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint);
if(mBorderWidth != 0){
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint);
}
}
然后看一下为了在onDraw函数里面实现如上图效果所做的一些初始化操作,这是就要看setup函数了
private void setup() {
if (!mReady) {
mSetupPending = true;
return;
}
if (mBitmap == null) {
return;
}
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBorderPaint.setStyle(Paint.Style.STROKE);//设画笔为空心
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
mBorderRect.set(0, 0, getWidth(), getHeight());
mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);//画圆形边框的半径
mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);
mDrawableRadius = Math.min(mDrawableRect.height() / 2, mDrawableRect.width() / 2);//画圆心位图的半径
updateShaderMatrix();
invalidate();
}
setup函数里关于半径的计算,举个例子:ImageView的宽高度均为150,边框的宽度为10,那么圆心位图的半径为65,圆形边框的半径为70,如图所示:
最后来看updateShaderMatrix函数,主要实现的功能是把原来的头像位图居中裁剪成圆形位图。首先将原头像位图按比例放缩至mDrawableRect这个矩形当中,使之能完整居中显示在mDrawableRect上。另一方面,如果有圆形边框的话,还要根据边框的宽度在x和y轴方向上对位图的位置做调整
private void updateShaderMatrix() {
float scale;
float dx = 0;
float dy = 0;
mShaderMatrix.set(null);
//根据已定义好的位图区域,按比例对原图缩放
if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
scale = mDrawableRect.height() / (float) mBitmapHeight;
dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
} else {
scale = mDrawableRect.width() / (float) mBitmapWidth;
dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
}
mShaderMatrix.setScale(scale, scale);//x和y轴上的缩放系数
mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth, (int) (dy + 0.5f) + mBorderWidth);//位图居中,留一点空间给边框
mBitmapShader.setLocalMatrix(mShaderMatrix);
}
承接上面的例子和数据,假设原图的宽度和高度为:200*300
执行完updateShaderMatrix,达到的效果: