今天來介紹Glide,開始吧(●´ϖ`●)
在開發 Android App 時,從網路載入圖片是一個非常常見的需求。如果直接處理網路連線、圖片解碼、快取等會非常繁瑣而且容易出錯。Glide是高效且開源的圖片載入函式庫,下面是他的幾個優點
基本呼叫:
with(context): 開始一個載入請求,並將其與傳入的 Context的生命週期綁定load(source): 指定圖片來源。來源可以是網路URL、Android 資源 ID、本地檔案路徑或 Uriinto(target): 指定要將圖片載入到哪個 ImageView 元件中老樣子先加入依賴
dependencies {
implementation 'com.github.bumptech.glide:glide:5.0.5'//or 其他版
annotationProcessor 'com.github.bumptech.glide:compiler:5.0.5'
}
接著在AndroidManifest.xml 中宣告網路權限
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:usesCleartextTraffic="true"
... >
</application>
</manifest>
然後放ImageView在layout中
activity_main.xml
<?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"
android:gravity="center">
<Button
android:id="@+id/load_main_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="載入圖片" />
<ImageView
android:id="@+id/image_main_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
最後在MainActivity.java,透過點擊按鈕來執行 Glide 載入圖片的程式碼
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private Button loadButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.image_main_iv);
loadButton = findViewById(R.id.load_main_btn);
loadButton.setOnClickListener(v -> loadImage());
}
private void loadImage() {
//圖片URL
String imageUrl = "https://media.makeameme.org/created/hello-nice-to-7a65209e71.jpg";
Glide.with(this) //指定 Context
.load(imageUrl) //指定圖片來源
.into(imageView); //指定要載入的 ImageView
}
}
private void loadAdvancedImage() {
String imageUrl = "https://media.makeameme.org/created/hello-nice-to-7a65209e71.jpg";
Glide.with(this)
.load(imageUrl)
.placeholder(R.drawable.XXX) // 載入期間顯示的圖片
.error(R.drawable.XXX) // 載入失敗時顯示的圖片
.into(imageView);
}
import com.bumptech.glide.request.RequestOptions;
private void loadCircleImage() {
String imageUrl = "https://media.makeameme.org/created/hello-nice-to-7a65209e71.jpg";
Glide.with(this)
.load(imageUrl)
.apply(RequestOptions.circleCropTransform()) // 套用圓形裁切
.into(imageView);
}
import com.bumptech.glide.load.engine.DiskCacheStrategy;
private void loadImageWithCacheControl() {
String imageUrl = "https://media.makeameme.org/created/hello-nice-to-7a65209e71.jpg";
Glide.with(this)
.load(imageUrl)
//DiskCacheStrategy.NONE:不使用磁碟快取
//DiskCacheStrategy.ALL:快取原始圖和轉換後的圖 (預設)
//DiskCacheStrategy.RESOURCE:只快取轉換後的圖
//DiskCacheStrategy.DATA:只快取原始圖
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true) //跳過記憶體快取
.into(imageView);
}
Glide就介紹到這裡,明天會來介紹Retrofit 搭配 RxJava,也是這次鐵人賽最後一個介紹的東西,最後一天就是結語了,明天見囉( ^ w •)
倒數兩天了! :)
