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

阅读 2033
收藏 97
2016-05-20
原文链接:blog.csdn.net

版权声明:本文为博主原创文章,未经博主允许不得转载。

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

这里写图片描述

配置方法

MAVEN

  com.squareup.picasso
  picasso
  (insert latest version)

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) {
      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。
资源文件的加载
       除了加载网络图片以外,picasso还支持加载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加载图片案例

这里写图片描述

首先在dependencies 中添加Picasso相关配置

compile ‘com.squareup.picasso:picasso:2.5.2’

然后上源码:

ListViewActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by huangshuai on 2016/5/20.
 * Email:huangshuai@wooyun.org
 * 列表Activity
 */
public class ListViewActivity extends AppCompatActivity {

    private ListView lv_main;
    private List listDatas;
    private SunAdapter lAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_view);
        lv_main = (ListView) findViewById(R.id.list_sun);
        listDatas = new ArrayList<>();
        initData();
        lAdapter = new SunAdapter(listDatas, this);
        lv_main.setAdapter(lAdapter);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        SunBean sun1 = new SunBean();
        sun1.setTitle("太阳的后裔一");
        sun1.setPicUrl("http://img3.imgtn.bdimg.com/it/u=3746050745,4184822198&fm=11&gp=0.jpg");
        listDatas.add(sun1);

        SunBean sun2 = new SunBean();
        sun2.setTitle("太阳的后裔二");
        sun2.setPicUrl("http://cdn.duitang.com/uploads/item/201603/02/20160302223503_jmdXT.thumb.224_0.jpeg");
        listDatas.add(sun2);

        SunBean news3 = new SunBean();
        news3.setTitle("太阳的后裔三");
        news3.setPicUrl("http://img5.duitang.com/uploads/item/201602/23/20160223132131_RNSQ3.thumb.224_0.jpeg");
        listDatas.add(news3);

        SunBean sun4 = new SunBean();
        sun4.setTitle("太阳的后裔四");
        sun4.setPicUrl("http://img5.duitang.com/uploads/item/201603/03/20160303163634_iveUE.thumb.224_0.jpeg");
        listDatas.add(sun4);

        SunBean sun5 = new SunBean();
        sun5.setTitle("太阳的后裔五");
        sun5.setPicUrl("http://cdn.duitang.com/uploads/item/201603/07/20160307013640_FQCTc.thumb.224_0.jpeg");
        listDatas.add(sun5);

        SunBean sun6 = new SunBean();
        sun6.setTitle("太阳的后裔六");
        sun6.setPicUrl("http://img4.duitang.com/uploads/item/201603/03/20160303102359_vzwPC.thumb.224_0.jpeg");
        listDatas.add(sun6);

        SunBean news7 = new SunBean();
        news7.setTitle("太阳的后裔七");
        news7.setPicUrl("http://img4.duitang.com/uploads/item/201603/03/20160303101132_AMPRv.thumb.224_0.jpeg");
        listDatas.add(news7);

        SunBean sun8 = new SunBean();
        sun8.setTitle("太阳的后裔八");
        sun8.setPicUrl("http://img0.imgtn.bdimg.com/it/u=1043934750,464206674&fm=11&gp=0.jpg");
        listDatas.add(sun8);
    }


}

SunAdapter.java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * Created by huangshuai on 2016/5/20.
 * Email:huangshuai@wooyun.org
 * 列表Adapter
 */
public class SunAdapter extends BaseAdapter {

    private List list_sun;
    private LayoutInflater inflater;
    private Context context;

    public SunAdapter(List list_new, Context context) {
        this.list_sun = list_new;
        this.context = context;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return list_sun.size();
    }

    @Override
    public Object getItem(int position) {
        return list_sun.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ItemViewHodler viewHolder;
        if (convertView == null) {
            viewHolder = new ItemViewHodler();

            convertView = inflater.inflate(R.layout.list_item, null);
            viewHolder.title = (TextView) convertView.findViewById(R.id.item_title);
            viewHolder.pic = (ImageView) convertView.findViewById(R.id.item_pic);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ItemViewHodler) convertView.getTag();
        }

        viewHolder.title.setText(list_sun.get(position).getTitle());
        Picasso.with(context).load(list_sun.get(position).getPicUrl()).fit()
                .placeholder(R.mipmap.alibg)
                .error(R.mipmap.ic_launcher)
                .into(viewHolder.pic);

        return convertView;
    }


    class ItemViewHodler {
        TextView title;
        ImageView pic;
    }
}

SunBean.java

/**
 * Created by huangshuai on 2016/5/20.
 * Email:huangshuai@wooyun.org
 * 列表图片Bean
 */
public class SunBean {

    private String title;
    private String picUrl;

    public SunBean(String title, String picUrl) {
        this.title = title;
        this.picUrl = picUrl;
    }

    public SunBean() {
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPicUrl() {
        return picUrl;
    }

    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }
}

list_itmxml




    

    


list_view.xml



    


最后不要忘了增加网络权限

安卓开发高级技术交流QQ群:108721298 欢迎入群

微信公众号:mobilesafehome

(本公众号支持投票)

Android安全技术大本营

评论