溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Glide 的基本使用

發(fā)布時(shí)間:2020-07-17 06:31:16 來源:網(wǎng)絡(luò) 閱讀:756 作者:HZ90 欄目:開發(fā)技術(shù)
導(dǎo)入引用:
項(xiàng)目中引入Glide 圖片框架:

repositories {
  mavenCentral()
}
dependencies {
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:support-v4:19.1.0'
}

1. 如果你的項(xiàng)目使用了Volley:
    dependencies {
        compile 'com.github.bumptech.glide:volley-integration:1.3.1'
        compile 'com.mcxiaoke.volley:library:1.0.5'
    }
    
    然后在你的Application的onCreate加入
    Glide.get(this)
         .register(GlideUrl.class, InputStream.class,new VolleyUrlLoader.Factory(yourRequestQueue));

2. 如果你的項(xiàng)目使用OkHttp:

    dependencies {
        compile 'com.github.bumptech.glide:okhttp-integration:1.3.1'
        compile 'com.squareup.okhttp:okhttp:2.4.0'
    }
    
    然后在你的Application的onCreate加入
    Glide.get(this)
         .register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(new OkHttpClient()));
3. Glide 的使用:

    Glide.with(viewHolder.p_w_picpathView.getContext()) // 不光接受Context,還接受Activity 和 Fragment

        .load(url) // 圖片的加載地址

        .diskCacheStrategy(DiskCacheStrategy.ALL) // 緩存類型,ALL:讓Glide既緩存全尺寸又緩存其他尺寸

        .error(R.drawable.ic_person)//加載失敗是顯示的Drawable

        .placeholder()//loading時(shí)的Drawable

        .animate()//設(shè)置load完的動(dòng)畫

        .centerCrop()//中心切圓, 會(huì)填滿

        .fitCenter()//中心fit, 以原本圖片的長(zhǎng)寬為主

        .into(p_w_picpathView); // 顯示圖片的容器
4. 加載GIF圖片:

    Glide.with(context)
    .load(url)
    .asGif()
    .into(p_w_picpathView)

5. 加載Bitmap:

    可以用在設(shè)大圖的背景

    Bitmap theBitmap = Glide.with(context)
        .load(url)
        .asBitmap()
        .into(100, 100). // 寬、高
        .get();

6. 縮略圖 Thumbnail:

    縮略圖, 0.1f就是原本的十分之一

    Glide.with(context)
        .load(url)
        .thumbnail(0.1f)
        .into(p_w_picpathView)
7. 變換圖片的形狀:

    Glide.with(getApplicationContext())
        .load(URL)
        .transform(new CircleTransform(getApplicationContext())) // 顯示為圓形圖片
        .into(p_w_picpathView);

    public class CircleTransform extends BitmapTransformation {
            public CircleTransform(Context context) {
                super(context);
            }
     
            @Override
            protected Bitmap transform(BitmapPool pool, Bitmap toTransform,
                    int outWidth, int outHeight) {
                return circleCrop(pool, toTransform);
            }
     
            private static 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;
     
                // TODO this could be acquired from the pool too
                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 String getId() {
                return getClass().getName();
            }
        }
 
 加載圓形圖片時(shí),不能設(shè)置.centerCrop(),否則圓形不起作用。是不是所有的Transform都是這樣,我沒有測(cè)試
8. Glide的一下配置,比如圖片默認(rèn)的RGB_565效果,可以創(chuàng)建一個(gè)新的GlideModule將Bitmap格式轉(zhuǎn)換到ARGB_8888:
    public class GlideConfiguration implements GlideModule {    
          
            @Override
        public void applyOptions(Context context, GlideBuilder builder) {
            // Apply options to the builder here.
    
            /**
             * Disk Cache 緩存配置
             */
            // 配置緩存大小:InternalCacheDiskCacheFactory
            builder.setDiskCache(new InternalCacheDiskCacheFactory(context, yourSizeInBytes));
            // 配置內(nèi)存緩存
            builder.setDiskCache(new InternalCacheDiskCacheFactory(context, cacheDirectoryName, 
                    yourSizeInBytes));
            // 配置外部緩存
            builder.setDiskCache(new ExternalCacheDiskCacheFactory(context, cacheDirectoryName, 
                    yourSizeInBytes));
    
            // 自定義配置
            // If you can figure out the folder without I/O:
            // Calling Context and Environment class methods usually do I/O.
            builder.setDiskCache(new DiskLruCacheFactory(getMyCacheLocationWithoutIO(), 
                    yourSizeInBytes));
    
            // In case you want to specify a cache folder ("glide"):
            builder.setDiskCache(new DiskLruCacheFactory(getMyCacheLocationWithoutIO(), "glide", 
                    yourSizeInBytes));
    
            // In case you need to query the file system while determining the folder:
            builder.setDiskCache(new DiskLruCacheFactory(new CacheDirectoryGetter() {
                @Override
                public File getCacheDirectory() {
                    return getMyCacheLocationBlockingIO();
                }
            }), yourSizeInBytes);
    
        }
    
        // 如果你要?jiǎng)?chuàng)建一個(gè)完全自定義的緩存,可以實(shí)現(xiàn)DiskCache.Factory接口,并且使用DiskLruCacheWrapper創(chuàng)建緩存位置
        builder.setDiskCache(new DiskCache.Factory() {
            @Override public DiskCache build () {
                File cacheLocation = getMyCacheLocationBlockingIO();
                cacheLocation.mkdirs();
                return DiskLruCacheWrapper.get(cacheLocation, yourSizeInBytes);
            }
        });
    
        /**
         * Memory caches and pools 配置
         */
        // Size 默認(rèn)是MemorySizeCalculator控制的,可以自定義
        MemorySizeCalculator calculator = new MemorySizeCalculator(context);
        int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
        int defaultBitmapPoolSize = calculator.getBitmapPoolSize();
    
        //如果你想在應(yīng)用程序的某個(gè)階段動(dòng)態(tài)調(diào)整緩存內(nèi)存,可以通過選擇一個(gè)memorycategory通過使用setmemorycategory()
        Glide.get(context).setMemoryCategory(MemoryCategory.HIGH);
    
        // Memory Cache  可以通過setMemoryCache() 方法來設(shè)置緩存大小,或者使用自己的緩存; 
        // LruResourceCache是Glide的默認(rèn)實(shí)現(xiàn),可以通過構(gòu)造函數(shù)自定義字節(jié)大小
        builder.setMemoryCache(newLruResourceCache(yourSizeInBytes));
    
        // Bitmap Pool 通過setBitmapPool() 設(shè)置Bitmap池的大小,LruBitmapPool是Glide的默認(rèn)實(shí)現(xiàn)類,通過該類的構(gòu)造函數(shù)更改大小
        builder.setBitmapPool(new LruBitmapPool(sizeInBytes));
    
        // Bitmap Format 通過setDecodeFormat() 方法設(shè)置設(shè)置圖片質(zhì)量
        builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);
    
    
        @Override
        public void registerComponents(Context context, Glide glide) {
            // register ModelLoaders here.
        }
      }
      同時(shí)在AndroidManifest.xml中將GlideModule定義為meta-data
      meta-data android:name="com.inthecheesefactory.lab.glidepicasso.GlideConfiguration"
                android:value="GlideModule"/>
9. 特性
    你可以做到幾乎和Picasso一樣多的事情,代碼也幾乎一樣。
    
    Image Resizing尺寸
    
    // Glide
    .override(300, 200);
    Center Cropping
    
    
    // Glide
    .centerCrop();
    Transforming
    
    
    // Glide
    .transform(new CircleTransform(context))
    
    設(shè)置占位圖或者加載錯(cuò)誤圖:
    // Glide
    .placeholder(R.drawable.placeholder)
    .error(R.drawable.p_w_picpathnotfound)
    
10. 混淆文件的配置
    -keepnames class com.mypackage.GlideConfiguration
    # or more generally:
    #-keep public class * implements com.bumptech.glide.module.GlideModule
    
希望對(duì)剛開始使用Glide的猿友們有所幫助,后續(xù)使用中有什么問題,我會(huì)繼續(xù)添加的!


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI