1. 程式人生 > >Android利用glide載入圓形圖片,頭像的實現

Android利用glide載入圓形圖片,頭像的實現

主要是用到了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);
            }
        });