Android图片加载框架之Picasso
相信做Android开发的对Square公司一定不会陌生,大名鼎鼎的网络请求框架Retrofit就来源于它,今天学习的是该公司出品的图片加载框架Picasso。
项目地址
https://github.com/square/picasso
使用说明
http://square.github.io/picasso/
Gradle:
compile 'com.squareup.picasso:picasso:2.5.2'
ProGard混淆配置:
-dontwarn com.squareup.okhttp.**
简介
图片为Android应用增加必要的背景和视觉,Picasso使得你可以在应用中轻而易举地实现图片加载,只需一行代码!
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
许多在Android上图片加载常见的的陷阱都被Picasso自动的处理了:
adaper
中处理ImageView
循环和取消下载
特性
在Adapter中下载
自动检测Adapter重用并取消之前的下载
@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);
}
图片转换
转换图片以更好地适配布局并减少内存使用
Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)
你也可以指定定制的转换方式来实现更高级的效果
public class CropSquareTransformation implements Transformation {
@Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap result = Bitmap.createBitmap(source, x, y, size, size);
if (result != source) {
source.recycle();
}
return result;
}
@Override
public String key() {
return "square()";
}
}
传入该类的实例到transform
方法
占位图
Picasso同时支持了下载和出错的占位图供用户选择
Picasso.with(context)
.load(url)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(imageView);
出错占位图显示前一个请求会被重试三次
资源加载
支持Resources
, assets
, files
, content providers
作为图片源
Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
Picasso.with(context).load(new File(...)).into(imageView3);
调试指示
开发时可以打开彩带显示来指示图片源,在Picasso实例调用setIndicatorsEnabled(true)
即可

标签:
Picasso
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)