这里我们介绍一下加载图片的框架Picasso。
其实我觉得大家都很熟悉,这个我主要是自己写下给自己看。
首先是使用和大多数开源框架一样首先导入依赖:
compile 'com.squareup.picasso:picasso:2.5.2'
首先说下最基本的用法:
Picasso.with(context).load(imageUrl).into(imageView);
短短的一行代码为我们解决了很多问题:
1.自动将图像缓存在本地
2.通过图片压缩转换以减少内存消耗
3.自动处理了ImageView的回收,即自动取消不在视野范围内的ImageView视图资源的加载
现在给大家看下适配器的代码:
@Override
public void getView(int position, View convertView, ViewGroup parent) {
SquaredImageView view = (SquaredImageView) convertView;
if (view == null) {
view = new SquaredImageView(context);
}
String url = getItem(position);
Picasso.with(context).load(url).into(view);
}
只需要这么写,那么加载过的url图片就会自动存到缓冲中,并且在复用的时候直接从缓存中查找。因为这是默认设置的当然我们也可以设置不存到缓存中或不在缓存中查找如下:
Picasso.with(getApplication())
.load(mURL)
.memoryPolicy(NO_CACHE, NO_STORE)
.into(imageView);
其中memoryPolicy的NO_CACHE是指图片加载时放弃在内存缓存中查找,NO_STORE是指图片加载完不缓存在内存中。
好了介绍下其他的如剪裁:
Picasso.with(this).load(imageUrl).resize(500,500)into(imgeView1);
然后就是下载的时候和错误的时候的替代图片:
Picasso.with(this).load(imageUrl).resize(500,500).placeholder(R.drawable.black).error(R.mipmap.ic_launcher).into(imgeView1);
还可以加载本地的:
Picasso.with(this).load(R.mipmap.ic_launcher).into(imgeView1);
Picasso.with(this).load(R.drawable.ic_launcher).into(imgeView1);
Picasso.with(this).load("file:///android_asset/ic_launcher.png").into(imgeView1);
Picasso.wiht(context).load(new File(...)).into(imageView);
好了就说这么多,给大家推荐我的另一篇加载图片的优化说了就是关于这个的:
Picasso内存优化
转载于:https://blog.csdn.net/li15225271052/article/details/59760652