圖片加載Glide的使用以及簡單封裝
阿新 • • 發佈:2018-05-23
內存緩存 activit div ear ole center fault 以及 any 前言:
在正式開發中,我們需要網絡請求框架,Glide是最好的選擇相對於開發者,我們在開發中,
解決圖片的問題,使用Glide來進行解決顯示。
1. Glide的簡介
在泰國矩形的谷歌發布者論壇上,谷歌為我們介紹了一個叫Glide的圖片加載庫,
作者是bumptech。這個庫的運用在Goole的開源項目中,包括2014年goole I/O大會發布
的官方app.
2. Glide的優點
1)使用簡單
2)可支配度高,自適應程度強
3)支持常見的圖片格式 jpg png git webp
4)支持多種數據源,網絡,本地資源,assets等
5)高效緩存策略,支持Memory和Disk圖片緩存,默認bitmap格式采用RGB_565內存至少減少一半,
6)聲明周期集成,根據activity/Fragment生命周期自動管理請求
3. 簡單的使用
2.1 簡單加載網絡圖片
Glide
.with(this)
.load("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png")
.into(imageView);
2.2 Glide相對重要的功能
(1)禁止內存緩存:
.skipMemoryCache(true)
(2)清除內存緩存:
// 必須在UI線程中調用
Glide.get(context).clearMemory();
(3)禁止磁盤緩存:
.diskCacheStrategy(DiskCacheStrategy.NONE)
(4)清除磁盤緩存:
// 必須在後臺線程中調用,建議同時clearMemory()
Glide.get(applicationContext).clearDiskCache();
(5)獲取緩存大小:
new GetDiskCacheSizeTask(textView).execute(new File(getCacheDir(www.jcx127.cn ), DiskCache.Factory.DEFAULT_DISK_CACHE_DIR));
(6)指定資源的優先加載順序:
//優先加載
Glide
.with(context)
.load(heroImageUrl)
.priority(Priority.HIGH)
.into(imageViewHero);
//後加載
Glide
.with(context)
.load(itemImageUrl)
.priority(Priority.LOW)
.into(imageViewItem);
(7)先顯示縮略圖,再顯示原圖:
//用原圖的1/10作為縮略圖
Glide
.with(this)
.load("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png")
.thumbnail(0.1f)
.into(iv_0);
//用其它圖片作為縮略圖
DrawableRequestBuilder<Integer> thumbnailRequest = Glide
.with(this)
.load(R.drawable.news);
Glide.with(this)
.load("http://www.rbuluoyl.cn/ inthecheesefactory.com/uploads/source/nestedfragment/fragments.png")
.thumbnail(thumbnailRequest)
.into(iv_0);
2.3 使用步驟
1)在build.gradle中添加依賴(根據最新版本添加)
compile ‘com.github.bumptech.glide:glide:3.7.0‘
2)如果你的項目沒有support:v4, 需要添加support-v4依賴:
compile ‘com.android.support:support-v4:23.3.0‘
3)進行簡單的使用
Glide
.with(this)
.load("http://inthecheesefactory.com/ www.thd540.com/ u ploads/source/nestedfragment/fragments.png")
.into(imageView);
3. 進行簡單的封裝
3.1 創建一個工具類
public class ImageUtils { /* * 加載圖片 * */ public static void GlideUtils(Context context, String imageUrl, ImageView imageView) { if (imageUrl == null && imageUrl.trim().isEmpty()) { imageUrl = ""; } int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); imageView.measure(widthSpec,heightSpec); int measuredWidth = imageView.getMeasuredWidth(www.feifanyule.cn); int measuredHeight = imageView.getMeasuredHeight(www.120xh.cn ); RequestOptions requestOptions= new RequestOptions(www.yigouyule2.cn); requestOptions.placeholder(R.mipmap.ic_www.taohuayuan178.com launcher); requestOptions.error(R.drawable.load_error); requestOptions.centerCrop(www.thd178.com/); requestOptions.override(measuredWidth,measuredHeight); Glide.with(context) .load(imageUrl) .thumbnail(0.1f) .apply(requestOptions) .into(imageView); } }
3.2 使用
ImageUtils.GlideUtils(context,data.getImgUrl(),holder.imgUrl);
圖片加載Glide的使用以及簡單封裝