Glide的使用
Glide是google開發(fā)用于Android加載媒體的類庫滥朱,包括圖片,gif,video,已經(jīng)在很多項(xiàng)目中使用娇斩,靈活快速笆檀。下面我們看如何使用它,如果有什么不對的請不吝指教
-
導(dǎo)入到項(xiàng)目中
dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:24.1.1' compile 'com.github.bumptech.glide:glide:3.7.0' compile 'com.android.support:support-v4:24.1.1' }
Glide同樣需要Android Support Library v4武氓,請記得加上support-v4客蹋,不過現(xiàn)在項(xiàng)目基本都包含support-v4遣总。
-
加載圖片
Glide.with(this).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg") .asBitmap() .into(mImageView);
-
Glide的生命周期
Glide.with()
不僅僅只是Context
還可以是Activity
,Fragment
等埃脏,傳入后自動適配诗赌,Glide加載圖片是會隨著Activity
,Fragment
的生命周期,具體可以參考LifecycleListener
晌纫,所以推薦使用Activity
,Fragment
. -
設(shè)置圖片大小
.override(200,200)
可以設(shè)置加載圖片大小税迷,但是實(shí)際大小不一定是200x200,通過源碼分析下:在
BitmapRequestBuilder
中默認(rèn)的private Downsampler downsampler = Downsampler.AT_LEAST;
/** * Load and scale the image uniformly (maintaining the image's aspect ratio) so that the smallest edge of the * image will be between 1x and 2x the requested size. The larger edge has no maximum size. */ public static final Downsampler AT_LEAST = new Downsampler() { @Override protected int getSampleSize(int inWidth, int inHeight, int outWidth, int outHeight) { return Math.min(inHeight / outHeight, inWidth / outWidth); } @Override public String getId() { return "AT_LEAST.com.bumptech.glide.load.data.bitmap"; } };
然后在
Downsampler
中的decode
方法中,獲取的Bitmap大小變成1/sampleSize锹漱,倍數(shù)通過getSampleSize
計(jì)算所得箭养,options.inTempStorage = bytesForOptions; final int[] inDimens = getDimensions(invalidatingStream, bufferedStream, options); final int inWidth = inDimens[0]; final int inHeight = inDimens[1]; final int degreesToRotate = TransformationUtils.getExifOrientationDegrees(orientation); final int sampleSize = getRoundedSampleSize(degreesToRotate, inWidth, inHeight, outWidth, outHeight); final Bitmap downsampled = downsampleWithSize(invalidatingStream, bufferedStream, options, pool, inWidth, inHeight, sampleSize, decodeFormat); // BitmapFactory swallows exceptions during decodes and in some cases when inBitmap is non null, may catch // and log a stack trace but still return a non null bitmap. To avoid displaying partially decoded bitmaps, // we catch exceptions reading from the stream in our ExceptionCatchingInputStream and throw them here. final Exception streamException = exceptionStream.getException(); if (streamException != null) { throw new RuntimeException(streamException); } Bitmap rotated = null; if (downsampled != null) { rotated = TransformationUtils.rotateImageExif(downsampled, pool, orientation); if (!downsampled.equals(rotated) && !pool.put(downsampled)) { downsampled.recycle(); } }
inSampleSize 是 BitmapFactory.Options的屬性,應(yīng)該大家都知道哥牍。然后再看看怎么生成
.override(200,200)
毕泌,如果沒有設(shè)置Glide默認(rèn)是FitCenter
,查看FitCenter
可以看到圖片截取方式嗅辣。public class FitCenter extends BitmapTransformation { public FitCenter(Context context) { super(context); } public FitCenter(BitmapPool bitmapPool) { super(bitmapPool); } @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { return TransformationUtils.fitCenter(toTransform, pool, outWidth, outHeight); } @Override public String getId() { return "FitCenter.com.bumptech.glide.load.resource.bitmap"; } }
--
public static Bitmap fitCenter(Bitmap toFit, BitmapPool pool, int width, int height) { if (toFit.getWidth() == width && toFit.getHeight() == height) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "requested target size matches input, returning input"); } return toFit; } final float widthPercentage = width / (float) toFit.getWidth(); final float heightPercentage = height / (float) toFit.getHeight(); final float minPercentage = Math.min(widthPercentage, heightPercentage); // take the floor of the target width/height, not round. If the matrix // passed into drawBitmap rounds differently, we want to slightly // overdraw, not underdraw, to avoid artifacts from bitmap reuse. final int targetWidth = (int) (minPercentage * toFit.getWidth()); final int targetHeight = (int) (minPercentage * toFit.getHeight()); if (toFit.getWidth() == targetWidth && toFit.getHeight() == targetHeight) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "adjusted target size matches input, returning input"); } return toFit; } Bitmap.Config config = getSafeConfig(toFit); Bitmap toReuse = pool.get(targetWidth, targetHeight, config); if (toReuse == null) { toReuse = Bitmap.createBitmap(targetWidth, targetHeight, config); } // We don't add or remove alpha, so keep the alpha setting of the Bitmap we were given. TransformationUtils.setAlpha(toFit, toReuse); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "request: " + width + "x" + height); Log.v(TAG, "toFit: " + toFit.getWidth() + "x" + toFit.getHeight()); Log.v(TAG, "toReuse: " + toReuse.getWidth() + "x" + toReuse.getHeight()); Log.v(TAG, "minPct: " + minPercentage); } Canvas canvas = new Canvas(toReuse); Matrix matrix = new Matrix(); matrix.setScale(minPercentage, minPercentage); Paint paint = new Paint(PAINT_FLAGS); canvas.drawBitmap(toFit, matrix, paint); return toReuse; }
這里算出圖片的大泻撤骸:
final float widthPercentage = width / (float) toFit.getWidth(); final float heightPercentage = height / (float) toFit.getHeight(); final float minPercentage = Math.min(widthPercentage, heightPercentage);
測試中我們使用的圖片是1080x540,最終生成了200x100.設(shè)置
approximate()
對應(yīng)Downsampler.AT_LEAST
,asIs()
對應(yīng)Downsampler.NONE
,atMost()
對應(yīng)Downsampler.AT_MOST
,具體情況可查看Downsampler
-
圖片緩存策略
測試加載的圖片大小為1080x540澡谭,如果使用了
.override(200,200)
默認(rèn)緩存一張200x100的圖片,也就是默認(rèn)存儲結(jié)果RESULT
愿题,如果想要改變緩存的策略可以這樣設(shè)置:.diskCacheStrategy(DiskCacheStrategy.ALL)
DiskCacheStrategy 分別有以下幾種選擇,
ALL
緩存原圖和截取后的圖蛙奖,NONE
不緩存潘酗,SOURCE
只緩存原圖,RESULT
緩存截取后的圖:public enum DiskCacheStrategy { /** Caches with both {@link #SOURCE} and {@link #RESULT}. */ ALL(true, true), /** Saves no data to cache. */ NONE(false, false), /** Saves just the original data to cache. */ SOURCE(true, false), /** Saves the media item after all transformations to cache. */ RESULT(false, true); private final boolean cacheSource; private final boolean cacheResult; DiskCacheStrategy(boolean cacheSource, boolean cacheResult) { this.cacheSource = cacheSource; this.cacheResult = cacheResult; } /** * Returns true if this request should cache the original unmodified data. */ public boolean cacheSource() { return cacheSource; } /** * Returns true if this request should cache the final transformed result. */ public boolean cacheResult() { return cacheResult; } }
查看本地緩存如下:
如果圖片需要分享或需要原圖的建議緩存
ALL
雁仲,否則只緩存RESULT
仔夺。 -
Glide全局配置
-
創(chuàng)建
GlideModel
public class GlideConfigModule implements GlideModule { @Override public void applyOptions(Context context, GlideBuilder builder) { } @Override public void registerComponents(Context context, Glide glide) { } }
-
在
AndroidManifest.xml
的meta-data
配置GlideModule
<meta-data android:name="com.branch.www.glidedemo.GlideConfigModule" android:value="GlideModule"/>
-
解決
GlideModel
沖突有可能加入的library中也同樣配置了
GlideModule
,如果配置了多個(gè)會出現(xiàn)沖突,無法編譯運(yùn)行攒砖,解決方式可在AndroidManifest.xml
移除<meta-data android:name=”com.mypackage.MyGlideModule” tools:node=”remove” />
-
默認(rèn)Bitmap Format 是 RGB_565
為了降低內(nèi)存消耗缸兔,Glide默認(rèn)配置的Bitmap Format 為 RGB_565日裙,修改GlideBuilder's
setDecodeFormat
設(shè)置builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);
-
配置Disk緩存
使用GlideBuilder's
setDiskCache()
方法設(shè)置緩存目錄和大小。
默認(rèn)Glide使用InternalCacheDiskCacheFactory
惰蜜,默認(rèn)最大緩存250M昂拂,這是一個(gè)應(yīng)用內(nèi)部目錄的緩存,緩存的圖片只能本應(yīng)用可以有權(quán)獲取蝎抽。builder.setDiskCache( new InternalCacheDiskCacheFactory(context, yourSizeInBytes)); builder.setDiskCache( new InternalCacheDiskCacheFactory(context, cacheDirectoryName, yourSizeInBytes));
你也可以使用
ExternalCacheDiskCacheFactory
去設(shè)置SD卡緩存builder.setDiskCache( new ExternalCacheDiskCacheFactory(context, cacheDirectoryName, yourSizeInBytes));
或者使用DiskLruCacheFactory配置自己管理的緩存目錄和大小
// 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);
或者你想完全控制緩存可以通過實(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); } });
如果你不需要任何緩存可以使用
DiskCacheAdapter
或者自己實(shí)現(xiàn)DiskCache
,DiskCacheAdapter
內(nèi)部沒有任何實(shí)現(xiàn)樟结。 -
Bitmap Pool
為了避免Bitmap頻繁解碼,我們通常會在系統(tǒng)內(nèi)存中緩存一部分經(jīng)常使用的圖片精算。GlideBuilder's
setBitmapPool()
可以設(shè)置你想要的緩存策略瓢宦,緩存大小。例如我們常用的LRU策略灰羽。builder.setBitmapPool(new LruBitmapPool(sizeInBytes));
或?qū)崿F(xiàn)
BitmapPool
自定義一個(gè)吧驮履。Glide所有的基本配置都在
GlideModule
內(nèi),使用Glide提供的緩存方式如下:builder.setDiskCache(new DiskLruCacheFactory(dirPath, DiskCache.Factory.DEFAULT_DISK_CACHE_SIZE));
如果需要自定義實(shí)現(xiàn)
DiskCache.Factory
廉嚼。GlideModule 更多配置如下:
-
自定義加載
-
SimpleTarget
如果單純的想獲得Bitmap玫镐,顯不顯示或者其他再定,則可以使用
SimpleTarget
Glide.with(this).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg") .asBitmap() .diskCacheStrategy(DiskCacheStrategy.ALL) .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { } });
需要注意的是如果你想獲取Bitmap那么一定不想因?yàn)?code>Activity,
Fragment
的生命周期影響怠噪,因此Glide.with(context)
使用Context,同時(shí)為了避免內(nèi)存泄露建議SimpleTarget
使用靜態(tài)內(nèi)部類而不是內(nèi)部類(靜態(tài)內(nèi)部類不持有外部引用)恐似。 -
ViewTarget
如果想要在圖片加載完成后設(shè)置一些動畫則可以使用
ViewTarget
Glide.with(this).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg") .asBitmap() .override(500,500) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(new ViewTarget<ImageView, Bitmap>(mImageView) { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { this.view.setImageBitmap(resource); } });
如果
.asGif()
使用GlideDrawable
替換Bitmap
,同時(shí)ViewTarget
中包含onStart()
,onStop()
,onDestroy()
生命周期回調(diào)傍念。如果想要繼續(xù)保留默認(rèn)的特性可以相應(yīng)的使用
GlideDrawableImageViewTarget
在asGif()
之后矫夷,使用BitmapImageViewTarget
在asBitmap()
之后。
-
-
自定義url
通過
width
xheight
拼接url下載指定大小的圖片憋槐,或者根據(jù)屏幕大小選擇高双藕,中,低三種分別率的圖片url阳仔。使用http或https加載圖片可以繼承
BaseGlideUrlLoader
public interface MyDataModel { public String buildUrl(int width, int height); } public class MyUrlLoader extends BaseGlideUrlLoader<MyDataModel> { @Override protected String getUrl(MyDataModel model, int width, int height) { // Construct the url for the correct size here. return model.buildUrl(width, height); } }
MyDataModel
就相當(dāng)于我們的媒體model,里面有當(dāng)前媒體的類型(image/gif/video)忧陪,url等屬性。然后你可以在加載是這樣使用:
Glide.with(yourFragment) .using(new MyUrlLoader()) .load(yourModel) .into(yourView);
如果不想每次都使用
.using(new MyUrlLoader())
近范,可以在前面我們的GlideModule
中配置public class MyGlideModule implements GlideModule { ... @Override public void registerComponents(Context context, Glide glide) { glide.register(MyDataModel.class, InputStream.class, new MyUrlLoader.Factory()); } }
配置后加載時(shí)跳過
.using()
-
<span id="getBitmap">在后臺線程下載</span>
-
downloadOnly
downloadOnly
有異步版和同步版嘶摊,如果已經(jīng)在后臺線程中執(zhí)行必須同步版FutureTarget<File> future = Glide.with(applicationContext) .load(yourUrl) .downloadOnly(500, 500); File cacheFile = future.get();
這種方式在主線程中會阻塞主線程。如果想要在主線程中執(zhí)行可以使用前面講到的
SimpleTarget
Glide.with(this) .load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg") .downloadOnly(new SimpleTarget<File>() { @Override public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) { } });
-
into
使用into可以用于下載顺又,下面是在后臺線程中的使用:
Bitmap myBitmap = Glide.with(applicationContext) .load(yourUrl) .asBitmap() .centerCrop() .into(500, 500) .get()
如果想在主線程中使用同樣可以使用
SimpleTarget
-
-
清除緩存
Glide.get(getApplicationContext()).clearMemory(); Glide.get(getApplicationContext()).clearDiskCache();
-
怎么使緩存失效
有時(shí)我們并不是想要清理所有緩存更卒,只是app版本變動則原來的緩存可能不需要了,或本地圖片庫中圖片變更但是文件名地址沒有變則可能就出現(xiàn)繼續(xù)使用原來的縮略圖或
.override(200,200)
使用的小圖稚照,其實(shí)最好的情況是如果數(shù)據(jù)變更則相應(yīng)的改變url蹂空,如果不改變可以使用StringSignature
解決這個(gè)問題.-
通過版本使緩存失效
Glide.with(yourFragment) .load(yourFileDataModel) .signature(new StringSignature(yourVersionMetadata)) .into(yourImageView);
-
MediaStore
中的數(shù)據(jù)Glide.with(fragment) .load(mediaStoreUri) .signature(new MediaStoreSignature(mimeType, dateModified, orientation)) .into(view);
-
自定義
實(shí)現(xiàn)
Key
接口俯萌,重寫equals()
,hashCode()
和updateDiskCacheKey()
方法,可以參考StringSignature
或MediaStoreSignature
的實(shí)現(xiàn)上枕。
-
-
Transformations
-
默認(rèn)的Transformations
Fit center
相當(dāng)于Android's
ScaleType.FIT_CENTER.
Glide.with(yourFragment) .load(yourUrl) .fitCenter() .into(yourView);
Center crop
相當(dāng)于Android's
ScaleType.CENTER_CROP
Glide.with(yourFragment) .load(yourUrl) .centerCrop() .into(yourView);
-
自定義transformations
最簡單的方式是集成
BitmapTransformation
private static class MyTransformation extends BitmapTransformation { public MyTransformation(Context context) { super(context); } @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { Bitmap myTransformedBitmap = ... // apply some transformation here. return myTransformedBitmap; } @Override public String getId() { // Return some id that uniquely identifies your transformation. return "com.example.myapp.MyTransformation"; } }
然后使用
.transform(new MyTransformation(context))
Transformations 有各種豐富的效果咐熙。
BitmapTransformation
可以用于改變bitmap形狀,顏色辨萍,截取棋恼,放大,所有等操作锈玉。
-
-
設(shè)置占位圖和加載錯(cuò)誤圖
.placeholder(R.drawable.placeholder) .error(R.drawable.imagenotfound)
-
ProGuard
-keep public class * implements com.bumptech.glide.module.GlideModule -keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** { **[] $VALUES; public *; } -keepresourcexmlelements manifest/application/meta-data@value=GlideModule
-
相關(guān)問題問答
-
使用
downloadOnly
或into
-
是否支持Webp
Android 4.0 以上能支持
-
在
AndroidManifest.xml
的meta-data
配置GlideModule
是如何獲取的查看源碼在
Glide.get(Context)
public static Glide get(Context context) { if (glide == null) { synchronized (Glide.class) { if (glide == null) { Context applicationContext = context.getApplicationContext(); List<GlideModule> modules = new ManifestParser(applicationContext).parse(); GlideBuilder builder = new GlideBuilder(applicationContext); for (GlideModule module : modules) { module.applyOptions(applicationContext, builder); } glide = builder.createGlide(); for (GlideModule module : modules) { module.registerComponents(applicationContext, glide.registry); } } } } return glide; }
可以看到
GlideModule
的獲取在ManifestParser
同時(shí)也發(fā)現(xiàn)可以設(shè)置多個(gè)爪飘,不過同樣的配置后面的會覆蓋前面的。那么進(jìn)入ManifestParser
查看是怎么實(shí)現(xiàn)的拉背。public final class ManifestParser { private static final String GLIDE_MODULE_VALUE = "GlideModule"; private final Context context; public ManifestParser(Context context) { this.context = context; } public List<GlideModule> parse() { List<GlideModule> modules = new ArrayList<>(); try { ApplicationInfo appInfo = context.getPackageManager() .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); if (appInfo.metaData != null) { for (String key : appInfo.metaData.keySet()) { if (GLIDE_MODULE_VALUE.equals(appInfo.metaData.get(key))) { modules.add(parseModule(key)); } } } } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException("Unable to find metadata to parse GlideModules", e); } return modules; } private static GlideModule parseModule(String className) { Class<?> clazz; try { clazz = Class.forName(className); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Unable to find GlideModule implementation", e); } Object module; try { module = clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException("Unable to instantiate GlideModule implementation for " + clazz, e); } if (!(module instanceof GlideModule)) { throw new RuntimeException("Expected instanceof GlideModule, but found: " + module); } return (GlideModule) module; } }
-