通过案例快速学会Picasso图片缓存库

Picasso是Square公司为Android开发的图形缓存库,提供图片下载和缓存功能,支持异步加载、内存和硬盘缓存、图片转换等功能。在适配器中自动处理图片加载避免错位,允许自定义图片转换,并提供错误占位图片。配置简单,一行代码即可实现图片加载。同时,Picasso能加载资源文件,如从网络、Resources、assets和file等。加入Android高级技术交流群了解更多。
摘要由CSDN通过智能技术生成

       picasso是Square公司开源的一个Android图形缓存库,官网地址http://square.github.io/picasso/,可以实现图片下载和缓存功能。
       下载地址:https://github.com/square/picasso

这里写图片描述

配置方法

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

基本使用

       picasso仅需一行代码就能实现图片的异步加载

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

       Picasso不仅实现了图片异步加载的功能,还解决了android中加载图片时需要解决的一些常见问题:

  1. 在adapter中需要取消已经不在视野范围的ImageView图片资源的加载,否则会导致图片错位,Picasso已经解决了这个问题。
  2. 使用复杂的图片压缩转换来尽可能的减少内存消耗
  3. 自带内存和硬盘二级缓存功能

Picasso特性

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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值