Android自定义圆形头像
把一个bitmap对象图片转为一个圆形的图片,也看过其它的一些自定义圆形继承view啊,但是也是各种paint画来画去的。而这里继承的是Drawable,相比几十行代码就ok。但是对于性能来说,还真没试过,有时间的读者们可以尝试一下哪些方法比较好,可以介绍给小弟让我也多学习学习
public class CircleImageDrawable extends Drawable {
//定义画笔对象
private Paint mPaint;
//定义需要设置的属性
private int mWidth;
private int mBorderThick = 0;
private int mBorderColor = Color.WHITE;
/**
* 圆形bitmap
* @param bitmap
*/
public CircleImageDrawable(Bitmap bitmap) {
BitmapShader bitmapShader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setShader(bitmapShader);
mWidth = Math.min(bitmap.getWidth(), bitmap.getHeight());
}
/**
* 圆形bitmap,带白色外边框
* @param bitmap
* @param borderThick 边框厚度,建议为10
*/
public CircleImageDrawable(Bitmap bitmap, int borderThick) {
BitmapShader bitmapShader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setShader(bitmapShader);
mWidth = Math.min(bitmap.getWidth(), bitmap.getHeight());
mBorderThick = borderThick;
}
/**
* 圆形bitmap,带自定义颜色外边框
* @param bitmap
* @param borderThick 边框厚度,建议为10
* @param borderColor 边框的颜色,不给是默认白色
*/
public CircleImageDrawable(Bitmap bitmap, int borderThick, int borderColor) {
BitmapShader bitmapShader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setShader(bitmapShader);
mWidth = Math.min(bitmap.getWidth(), bitmap.getHeight());
mBorderThick = borderThick;
mBorderColor = borderColor;
}
@Override
public void draw(Canvas canvas) {
canvas.drawCircle(mWidth/2+mBorderThick, mWidth/2+mBorderThick, mWidth/2, mPaint);
if (mBorderThick != 0) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
paint.setColor(mBorderColor);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(mBorderThick);
canvas.drawCircle(mWidth/2+mBorderThick, mWidth/2+mBorderThick, mWidth/2+mBorderThick/2, paint);
}
}
@Override
public int getIntrinsicWidth() {
return mWidth + mBorderThick*2;
}
@Override
public int getIntrinsicHeight() {
return mWidth + mBorderThick*2;
}
@Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
在Activity中使用也是简单粗暴
ImageView iv;
Bitmap bm; //这里bm就不赋值了,反正就是一个Bitmap的对象而已
iv.setImageDrawable(new CircleImageDrawable(bm)); //用一个ImageView对象去调用就好了
就这些了,调用也不需要去xml布局文件中加载,直接一句代码就搞定。