Android 自定义圆形头像

CircleImageView类 :

public class CircleImageView extends ImageView {

    Path path;
    public PaintFlagsDrawFilter mPaintFlagsDrawFilter;// 毛边过滤
    Paint paint;
    public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
        init();
    }

    public CircleImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        init();
    }

    public CircleImageView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        init();
    }

    public void init() {
        paint = new Paint();
    }

    @Override
    protected void onDraw(Canvas cns) {
        // TODO Auto-generated method stub
        Drawable drawable = getDrawable();
        if (null != drawable) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            Bitmap b = circleDraw(bitmap);
            final Rect rect1 = new Rect(0, 0, b.getWidth(), b.getHeight());
            final Rect rect2 = new Rect(0, 0, getMeasuredWidth(), getMeasuredHeight());
            paint.reset();
            cns.drawBitmap(b, rect1, rect2, paint);
            b.recycle();
        } else {
            super.onDraw(cns);
        }
    }

    private Bitmap circleDraw(Bitmap bitmap) {
        int r=0;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Rect rectSource = null;
        if(width>height)
            r=height;
        else
        {
            r=width;
        }
        //创建一个图片对象
        Bitmap output = Bitmap.createBitmap(r, r, Bitmap.Config.ARGB_8888);
        //创建一个图片游标
        Canvas canvas = new Canvas(output);
        final Rect rect = new Rect(0, 0, r, r);
        /* 设置取消锯齿效果 */
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.WHITE);
        /* 绘画一个圆图形 */
        canvas.drawCircle(r/ 2, r / 2, r / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }
}

使用时在布局中使用自定义image即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值