Android圖片加載框架Picasso最全使用教程 一

Picasso介紹

Picasso是Square公司開源的一個Android圖形緩存庫

A powerful image downloading and caching library for Android
一個Android下強大的圖片下載緩存庫

Picasso實現了圖片的異步加載,並解決了Android中加載圖片時常見的一些問題,它有以下特點:

  • Adapter中取消了不在視圖範圍內的ImageView的資源加載,因爲可能會產生圖片錯位;
  • 使用複雜的圖片轉換技術降低內存的使用
  • 自帶內存和硬盤的二級緩存機制

爲什麼要用Picasso

  Android系統作爲圖片資源加載的主角,它是通過圖像的像素點來把圖像加載到內存中的;現在一張500W的攝像頭拍出的照片(2592x1936),加載到內存中需要大約19M的內存;如果你加入了信號強度不一的網絡中進行了複雜的網絡請求,並進行圖片的緩存與其他處理,你會耗費大量的時間與精力來處理這些問題,但如果用了Picasso, 這些問題都一消而散;

將Picasso加入到你的項目中

 目前Picasso的最新版本是2.5.2,你可以下載對應的Jar包,將Jar包添加到你的項目中,或者在build.gradle配置文件中加入

compile 'com.squareup.picasso:picasso:2.5.2'

注意如果你開啓了混淆,你需要將以下代碼添加到混淆規則文件中:

-dontwarn com.squareup.okhttp.**

小試牛刀:從網絡加載一張圖片

Picasso使用簡單易用的接口,並有一個實現類Picasso,一個完整的功能請求至少需要三個參數;

  • with(Context context) - Context上下文在很多Android Api中都是必須的
  • load(String imageUrl) - 圖片網絡加載地址
  • into(ImageView targetImageView) - 想進行圖片展示的ImageView

簡單用例:

ImageView targetImageView = (ImageView) findViewById(R.id.imageView);
String internetUrl = "http://www.jycoder.com/json/Image/1.jpg";

Picasso
    .with(context)
    .load(internetUrl)
    .into(targetImageView);

  就是這麼簡單,如果你的 URL地址正確並且圖片存在,在幾秒中之內就能看到這張圖片了;如果圖片資源不存在,Picasso也會有錯誤的回調,現在你已經看到了只需3行代碼就能加載圖片了,當然這只是冰山一角,讓我們繼續揭開Picasso的神祕面紗;

圖片的其他加載方式

  Picasso的圖片不僅僅能加載網絡資源,也能從本地文件,Android項目資源,以及URI地址進行圖片加載,下面我們就對這三種方式進行實例說明;

從Android Resources 中加載

  代碼也是三行,只需要將網絡資源地址更改爲一個int值地址即可,上代碼:

ImageView targetImageView = (ImageView) findViewById(R.id.imageView);
int resourceId = R.mipmap.ic_launcher;

Picasso
    .with(context)
    .load(resourceId)
    .into(targetImageView);

注意: R.mipmapAndroid Studio中新的資源引用路徑,這個老司機都知道.

從本地File文件中加載

  如果你讓用戶選擇本地的一張圖片進行展示的話,就需要用到這個加載方式了,當然,也是So Easy,只需要將地址更換爲一個File即可,上代碼:

ImageView targetImageView = (ImageView) findViewById(R.id.imageView);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Running.jpg");

Picasso
    .with(context)
    .load(file)
    .into(targetImageView); 

注意:這個file並不一定非得是在你的設備中,可以是任意的路徑,只要是File路徑即可;

URI地址中加載

  這個請求方式相比其他也並沒有什麼不同,上代碼:

public static final String ANDROID_RESOURCE = "android.resource://";
public static final String FOREWARD_SLASH = "/";

private static Uri resourceIdToUri(Context context, int resourceId) {
    return Uri.parse(ANDROID_RESOURCE + context.getPackageName() + FOREWARD_SLASH + resourceId);
}

Uri uri = resourceIdToUri(context, R.mipmap.future_studio_launcher);
ImageView targetImageView = (ImageView) findViewById(R.id.imageView);

Picasso  
    .with(context)
    .load(uri)
    .into(targetImageView);

注意:爲了示範,只能用資源文件轉換爲URI,並不僅僅是這種方式, 它可以支持任意的URI地址;

OK,到此我們已經對Picasso有一個基本的認識和了解了,跟着我的腳步,繼續發現Picasso更多好玩的功能,下面會介紹Picasso在ListViewGridView的用法,願大家都有美好的一天~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章