圖片加載<第七篇>:Glide4基本使用

(1)添加依賴

Glide最新版本已經(jīng)更新到4.9了。

implementation 'com.github.bumptech.glide:glide:4.9.0'
(2)權(quán)限

加載網(wǎng)絡(luò)需要用到網(wǎng)絡(luò)權(quán)限:

<uses-permission android:name="android.permission.INTERNET"/>
(3)解決Android8.0以上手機(jī)加載圖片問題
String url = "http://pic32.nipic.com/20130823/13339320_183302468194_2.jpg";
Glide.with(this).load(url).into(image_view);

以上代碼比較簡(jiǎn)單,但是Android8.0以上的手機(jī)會(huì)出現(xiàn)如下問題:

圖片.png

原因是:Android引入了對(duì)Https的推薦支持,而Android 8.0以上系統(tǒng)上面默認(rèn)所有Http的請(qǐng)求都被阻止了方法。
解決辦法:在AnroidManifest.xml中的application設(shè)置

android:usesCleartextTraffic="true"

效果如下:

58.gif
(4)with方法介紹
圖片.png

Glide.with()可以拿到加載圖片的實(shí)例,也就是RequestManager實(shí)例。
with支持傳遞view、application context、activity、fragment、fragmentactivity。

view: 基于某view獲取RequestManager實(shí)例,當(dāng)view被銷毀時(shí),Glide停止加載圖片;
application context: 基于某application context獲取RequestManager實(shí)例,當(dāng)app進(jìn)程被殺時(shí),Glide停止加載圖片;
activity: 基于某activity獲取RequestManager實(shí)例,當(dāng)activity被銷毀時(shí),Glide停止加載圖片;
fragment: 基于某fragment獲取RequestManager實(shí)例,當(dāng)fragment被銷毀時(shí),Glide停止加載圖片;(只支持support.v4)
fragmentactivity: 基于某fragmentactivity獲取RequestManager實(shí)例,當(dāng)fragmentactivity被銷毀時(shí),Glide停止加載圖片;(只支持support.v4)

(5)圖片加載

使用load加載圖片

圖片.png

如上圖,Glide可以加載Uri、File、二進(jìn)制流、Bitmap、字符串、Drawable、項(xiàng)目資源。

代碼如下:

    //加載網(wǎng)絡(luò)圖片
    String url = "http://pic32.nipic.com/20130823/13339320_183302468194_2.jpg";
    Glide.with(this).load(url).into(image_view);

    //加載本地文件
    File file = new File(FileDirUtil.getInstance().getExternalStorageDirectory() + File.separator + "temp.jpg");
    Glide.with(this).load(file).into(image_view);

    //加載bitmap
    Bitmap bitmap = AssetsFileUtil.getImageFromAssetsFile(this, "ic_launcher.png");
    Glide.with(this).load(bitmap).into(image_view);

    //加載字節(jié)流
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
        byte[] cache = new byte[10240];
        int index = 0;
        while ((index = fis.read(cache)) != -1){
            baos.write(cache, 0, index);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(fis != null){
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    if(baos != null){
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Glide.with(this).load(baos.toByteArray()).into(image_view);

    //加載Drawable
    Glide.with(this).load(getResources().getDrawable(R.mipmap.ic_launcher)).into(image_view);

    //加載資源
    Glide.with(this).load(R.mipmap.ic_launcher).into(image_view);

    // 加載Uri對(duì)象
    Uri imageUri = getImageUri();
    Glide.with(this).load(imageUri).into(imageView);
(6)占位圖

加載網(wǎng)絡(luò)圖片可能因?yàn)榫W(wǎng)絡(luò)原因加載的比較慢,為了增加用戶體驗(yàn),可添加一張本地圖片占位,Glide可以實(shí)現(xiàn)占位圖效果

//加載網(wǎng)絡(luò)圖片
String url = "http://pic32.nipic.com/20130823/13339320_183302468194_2.jpg";
Glide.with(this)
        .load(url)
        .placeholder(R.mipmap.ic_launcher)
        .into(image_view);
(7)磁盤緩存策略

磁盤緩存策略有:

  • DiskCacheStrategy.NONE: 表示不緩存任何內(nèi)容。
  • DiskCacheStrategy.DATA: 表示只緩存原始圖片。
  • DiskCacheStrategy.RESOURCE: 表示只緩存轉(zhuǎn)換過后的圖片。
  • DiskCacheStrategy.ALL : 表示既緩存原始圖片,也緩存轉(zhuǎn)換過后的圖片。
  • DiskCacheStrategy.AUTOMATIC: 表示讓Glide根據(jù)圖片資源智能地選擇使用哪一種緩存策略(默認(rèn)選項(xiàng))。

代碼如下:

圖片.png
(8)異常占位圖

加載網(wǎng)絡(luò)圖片異常時(shí)所展示的圖,url的網(wǎng)絡(luò)資源圖片不存在時(shí)可以觸發(fā)。

圖片.png
(9)限制加載

限制只允許加載靜態(tài)圖

圖片.png

限制只允許加載GIF

圖片.png

限制只允許加載Drawable

圖片.png

限制只允許加載文件

圖片.png
(10)修改圖片分辨率

假如圖片本身的分辨率是1000x800,要求在200x200的Imageview控件展示,一般我們直接展示即可,但是圖片的展示是非常消耗內(nèi)存的,所以為了節(jié)省內(nèi)存我們一般先將圖片壓縮到200x160,這樣既可以保證圖片展示不失真,而且避免了內(nèi)存的浪費(fèi)。

使用Glide的override方法,可以修改圖片的分辨率,保證內(nèi)存沒必要的浪費(fèi)。一般我們將寬和高設(shè)置成Imageview控件的大小一致即可。

圖片.png
圖片.png
(11)縮略圖
圖片.png

先加載縮略圖,再加載原圖,和placeholder類似。

(12)RequestOptions的使用

沒有使用RequestOptions的情況:

//加載網(wǎng)絡(luò)圖片
String url = "http://pic32.nipic.com/20130823/13339320_183302468194_2.jpg";
Glide.with(this)
        .load(url)
        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
        .error(R.mipmap.ic_launcher)
        .override(500)
        .transform(new GlideRoundTransform())//將圖片變形為圓形
        .into(image_view);

使用RequestOptions的情況:

//加載網(wǎng)絡(luò)圖片
String url = "http://pic32.nipic.com/20130823/13339320_183302468194_2.jpg";
RequestOptions options = new RequestOptions();
options.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
    .error(R.mipmap.ic_launcher)
    .override(500)
     .transform(new GlideRoundTransform());//將圖片變形為圓形
Glide.with(this)
         .load(url)
        .apply(options)
        .into(image_view);

以上兩種寫法對(duì)比之后就知道怎么玩RequestOptions了。

(13)優(yōu)先級(jí)

設(shè)置優(yōu)先級(jí)的代碼如下:

圖片.png
(14)圖片轉(zhuǎn)換
圖片.png

如圖所示,transform可以設(shè)置圖片的轉(zhuǎn)換類。

這里提供兩種常用的圖片轉(zhuǎn)換,即圓形圖片圓角圖片

/**
 * 圓形圖片的轉(zhuǎn)換類
 */
public class GlideCircleTransform extends BitmapTransformation {


    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return circleCrop(pool, toTransform);
    }

    private Bitmap circleCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;
        int size = Math.min(source.getWidth(), source.getHeight());
        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;
        Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
        Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        }
        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);
        return result;
    }


    @Override
    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {

    }
}


/**
 * 圓角圖片的轉(zhuǎn)換類
 */
public class GlideRoundTransform extends BitmapTransformation {

    private float radius = 0f;

    public GlideRoundTransform() {
        this(4);
    }
    public GlideRoundTransform(int radiusDp) {
        super();
        this.radius = Resources.getSystem().getDisplayMetrics().density * radiusDp;
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return roundCrop(pool, toTransform);
    }
    private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;
        Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        }
        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
        canvas.drawRoundRect(rectF, radius, radius, paint);
        return result;
    }

    @Override
    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {

    }
}

兩種轉(zhuǎn)換類的效果分別是

圖片.png
圖片.png
(15)加入動(dòng)畫

Glide的transition方法可以添加圖片的動(dòng)畫效果。

  • DrawableTransitionOptions 設(shè)置淡入淡出動(dòng)畫
圖片.png

假如代碼這樣寫

.transition(DrawableTransitionOptions.withCrossFade(3000))

效果如下:

59.gif
  • GenericTransitionOptions 其它動(dòng)畫
圖片.png

可以添加補(bǔ)間動(dòng)畫和屬性動(dòng)畫,這個(gè)就不演示效果了,動(dòng)畫效果實(shí)在是太多了。

(16)清除緩存
//清除硬盤緩存
Glide.get(this).clearDiskCache();
//清除內(nèi)存緩存
Glide.get(this).clearMemory();
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容