Android利用glide加载圆形图片,头像的实现

时间:2022-06-14 23:14:28

主要是用到了RoundedBitmapDrawable这个类是Drawable的一个子抽象类
可以实现从文件路径,输入流或bitmap 的对象都可以转换成圆形,或圆角,就不用使用第三方了,很方便
如果要转换成圆形,要用到下面这个方法;

/** * Sets the image shape to circular. * <p>This overwrites any calls made to {@link #setCornerRadius(float)} so far.</p> */
    public void setCircular(boolean circular) {
        mIsCircular = circular;
        mApplyGravity = true;
        if (circular) {
            updateCircularCornerRadius();
            mPaint.setShader(mBitmapShader);
            invalidateSelf();
        } else {
            setCornerRadius(0);
        }
    }

下面这个是类的说明,可以看一下

/**
 * A Drawable that wraps a bitmap and can be drawn with rounded corners. You can create a
 * RoundedBitmapDrawable from a file path, an input stream, or from a
 * {@link android.graphics.B或itmap} object.
 * <p>
 * Also see the {@link android.graphics.Bitmap} class, which handles the management and
 * transformation of raw bitmap graphics, and should be used when drawing to a
 * {@link android.graphics.Canvas}.
 * </p>
 */

具体的使用如下配合glide

//加载圆形头像
        Glide.with(context).load(data.get(position).getMenu_img().toString())
                .asBitmap().centerCrop().into(new BitmapImageViewTarget(holder.gridIcon) {
            @Override
            protected void setResource(Bitmap resource) {
                RoundedBitmapDrawable circularBitmapDrawable =
                        RoundedBitmapDrawableFactory.create(context.getResources(), resource);
                circularBitmapDrawable.setCircular(true);
                holder.gridIcon.setImageDrawable(circularBitmapDrawable);
            }
        });