Android 两款不错的图片加载库使用详解

这两款加载库分别是Glide和Picasso。按需使用,优缺点不一。

导入库Picasso:

dependencies {compile ‘com.squareup.picasso:picasso:2.5.1’ }

导入库Glide: Glide需要依赖Support Library v4,别忘了。

dependencies {compile ‘com.github.bumptech.glide:glide:3.5.2’compile ‘com.android.support:support-v4:22.0.0’ } Glide和Picasso加载图片的方法非常相似。Picasso.with(context).load(“http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg”).into(ivImg); Glide.with(context).load(“http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg”).into(ivImg);虽然两者看起来一样,但是Glide更易用,因为Glide的with方法不光接受Context,还接受Activity 和 Fragment,Context会自动的从他们获取。同时将Activity/Fragment作为with()参数的好处是:图片加载会和Activity/Fragment的生命周期保持一致,比如Paused状态在暂停加载,在Resumed的时候又自动重新加载。所以我建议传参的时候传递Activity 和 Fragment给Glide,而不是Context。Glide默认的Bitmap格式是RGB_565 ,比ARGB_8888格式的内存开销要小一半。如果你觉得难以接受,可以创建一个新的GlideModule将Bitmap格式转换到ARGB_8888:public class GlideConfiguration implements GlideModule {@Overridepublic void applyOptions(Context context, GlideBuilder builder) {// Apply options to the builder here. builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);}@Overridepublic void registerComponents(Context context, Glide glide) {// register ModelLoaders here. } } Picasso是加载了全尺寸的图片到内存,然后让GPU来实时重绘大小。而Glide加载的大小和ImageView的大小是一致的,因此更小。当然,Picasso也可以指定加载的图片大小的:Picasso.with(this).load(“http://nuuneoi.com/uploads/source/playstore/cover.jpg”).resize(768, 432).into(ivImgPicasso); 但是问题在于你需要主动计算ImageView的大小,或者说你的ImageView大小是具体的值(而不是wrap_content),你也可以这样:Picasso.with(this).load(“http://nuuneoi.com/uploads/source/playstore/cover.jpg”).fit().centerCrop().into(ivImgPicasso); Picasso和Glide在磁盘缓存策略上有很大的不同。Picasso缓存的是全尺寸的,而Glide缓存的是跟ImageView尺寸相同的。上面提到的平滑度的问题依然存在,而且如果加载的是RGB565图片,那么缓存中的图片也是RGB565。不过,你可以让Glide既缓存全尺寸又缓存其他尺寸:Glide.with(this).load(“http://nuuneoi.com/uploads/source/playstore/cover.jpg”).diskCacheStrategy(DiskCacheStrategy.ALL).into(ivImgGlide);Glide它远比Picasso快,但需要更大的空间来缓存。

每一发奋努力的背后,必有加倍的赏赐。

Android 两款不错的图片加载库使用详解

相关文章:

你感兴趣的文章:

标签云: