1. 程式人生 > >Android圖片載入框架Glide的簡單用法

Android圖片載入框架Glide的簡單用法

一、概述

Glide是一款由Bump Technologies開發的圖片載入框架,可以在android平臺上以很簡單的方式載入和展示圖片。

目前,Glide最新的穩定版本是3.7.0,這個版本的Glide相當成熟和穩定。

二、準備工作

android studio使用者,在app/build.gradle檔案當中新增如下依賴:

compile 'com.github.bumptech.glide:glide:3.7.0'

Eclipse使用者,下載Glide的jar包連結:

http://download.csdn.net/download/sinyu890807/9781538

Glide需要用到網路功能,得在AndroidManifest.xml中宣告一下網路許可權:


<uses-permissionandroid:name="android.permission.INTERNET"/>

三、使用方法

佈局檔案,在佈局當中加入一個Button和一個ImageView,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下載圖片" android:onClick="onClick"/> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
MainActivity中的程式碼
package com.example.glidetest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView= (ImageView) findViewById(R.id.image);
}
    public void onClick(View view){
        //url是你的圖片連結
String url="http://cn.bing.com/az/hprichbg/rb/Dongdaemun_ZH-CN10736487148_1920x1080.jpg";
Glide.with(this).load(url).into(imageView);
}
}

很簡單的一行程式碼。執行一下程式,效果如下圖所示:
點選下載圖片後加載圖片
核心的程式碼就只有這一行:
Glide.with(this).load(url).into(imageView);

下面我們就來詳細解釋一下這行程式碼

呼叫Glide.with()方法用於建立一個載入圖片的例項。with()方法可以接收Context、Activity或者Fragment型別的

引數。也就是說我們選擇的範圍非常廣,不管是在Activity還是Fragment中呼叫with()方法,都可以直接傳this。

那如果呼叫的地方既不在Activity中也不在Fragment中,也沒關係,我們可以獲取當前應用程式的

ApplicationContext,傳入到with()方法當中。

load()方法用於指定待載入的圖片資源。Glide支援載入各種各樣的圖片資源,包括網路圖片、本地圖片、

應用資源、二進位制流、Uri物件等。

// 載入本地圖片
File file = new File(getExternalCacheDir() + "/image.jpg");
Glide.with(this).load(file).into(imageView);

// 載入應用資源
int resource = R.drawable.image;
Glide.with(this).load(resource).into(imageView);

// 載入二進位制流
byte[] image = getImageBytes();
Glide.with(this).load(image).into(imageView);

// 載入Uri物件
Uri imageUri = getImageUri();
Glide.with(this).load(imageUri).into(imageView);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

into()方法就很簡單了,我們希望讓圖片顯示在哪個ImageView上,把這個ImageView的例項傳進去就可以了。

Glide最基本的使用方式,其實就是關鍵的三步走:先with(),再load(),最後into()。