Android自定义Drawable实现圆形头像
2015-05-30史琪锴盛萍萍
史琪锴 盛萍萍
以前看到许多圆形头像是通过自定义ImageView来实现的,现在,只要自定义Drawable,几行代码即可实现效果:
代码如下:
public class RoundImageDrawable extends Drawable {
private Paint myPaint;
private Bitmap bitmap;
private int width;
public RoundImageDrawable(Bitmap bitmap){
this.bitmap=bitmap;
myPaint =new Paint();
BitmapShader bs =new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP);//设置以何种方式重复
myPaint.setAntiAlias(true);
myPaint.setShader(bs);
//取寬高中较小的一个作为直径,当然为了防止OOM可以先用BitmapFactory.options解析一下压缩图片
width =Math.min(bitmap.getWidth(), bitmap.getHeight());
}
//注意不是自定义View,不是复写OnDraw()方法
@Override
public void draw(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawCircle(width/2, width/2,width/2, myPaint);
//这里是圆心和半径,并指定画笔
}
@Override
public int getIntrinsicWidth() {
// TODO Auto-generated method stub
return width;
}
@Override
public int getIntrinsicHeight() {
// TODO Auto-generated method stub
return width;
}
@Override
public void setAlpha(int alpha) {
// TODO Auto-generated method stub
myPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter cf) {
// TODO Auto-generated method stub
myPaint.setColorFilter(cf);
}
@Override
public int getOpacity() {
// TODO Auto-generated method stub
return PixelFormat.TRANSLUCENT;
}
}
是不是很简单呢?用法更简单:
img=(ImageView) findViewById(R.id.image);
img.setImageDrawable(new RoundImageDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.资源ID)));
以后再想使用圆形头像再也不用使用第三方库了!