Picasso-Android图片缓存库

Picasso官方网址:http://square.github.io/picasso/

介绍

在Android应用程序中使用Picasso添加图片必须要有上下文(context)和图片来源。仅仅只需要一行代码就能完全实现图片的异步加载!

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

Picasso能帮你处理许多在Android图片加载中遇到的常见问题:

  • 在adapter中需要取消已经不在视野范围的ImageView图片资源的加载(避免导致图片错位)。
  • 使用复杂的图片压缩转换来尽可能的减少内存消耗。
  • 自带内存和硬盘二级缓存功能。

这里写图片描述

特性

Adapter中的下载

Adapter的重用会被自动检测到,Picasso会取消上次的加载。

@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()"; }
}

将CropSquareTransformation 的对象传递给transform方法即可。

Place holders(占位图)

Picasso提供了两种占位图片,加载未完成或者加载发生错误的占位图,这两个为可选属性。

Picasso.with(context)
    .load(url)
    .placeholder(R.drawable.user_placeholder)
    .error(R.drawable.user_placeholder_error)
    .into(imageView);

如果加载发生错误会重复三次请求,三次都失败才会显示erro Place holder。

加载资源

资源(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) 来实现。

Debug ribbon indicators

MAVEN

<dependency>
  <groupId>com.squareup.picasso</groupId>
  <artifactId>picasso</artifactId>
  <version>(insert latest version)</version>
</dependency>

GRADLE

compile 'com.squareup.picasso:picasso:(insert latest version)'
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值