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);

出错占位图显示前一个请求会被重试三次

资源加载

支持Resourcesassetsfilescontent 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)即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值