超简洁代码实现CircleImageView

效果图:

这里写图片描述

页面代码:

public class CircleView extends ImageView {
    private Paint mPaint = new Paint();

    public CircleView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        Drawable mDrawable = getDrawable();//获取xml文件设置的图片
        if (null == mDrawable) super.onDraw(canvas);//如果为空,交给父类处理
        Bitmap mBitmap = ((BitmapDrawable) mDrawable).getBitmap();//将图片转化成bitmap

        int len = getWidth() < getHeight() ? getWidth() : getHeight();//获取xml的长宽属性值,选择较小的

        Bitmap tempBitmap = Bitmap.createBitmap(len, len, Bitmap.Config.ARGB_8888);//新建一个bitmap对象,作为缓存
        Canvas mCanvas = new Canvas(tempBitmap);//新建画布缓存bitmap对象

        mPaint.setAntiAlias(true);//抗锯齿
        mCanvas.drawCircle(len / 2, len / 2, len / 2, mPaint);//画一个圆

        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));//设置画笔的覆盖类型

        Matrix matrix = new Matrix(); // 初始化Matrix对象
        matrix.setScale((float) len / mBitmap.getWidth(), (float) len / mBitmap.getHeight()); //设置缩放比例
        mCanvas.drawBitmap(mBitmap, matrix, mPaint);//画出缩放后的图片

        mPaint.reset();//重置画笔
        canvas.drawBitmap(tempBitmap, 0, 0, mPaint);//绘制缓存图片
    }

}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值