編輯:關於 Android 程式設計
本文為大家分享 Android Glide 圖片載入的具體程式碼,涵蓋載入監聽與自訂動畫,供有需要的人參考。
1. 普通用法
Glide.with(context) .load(url) .into(view);
with 中可以放 context、activity、fragment……當放 activity、fragment 時,Glide 會依生命週期來載入圖片,因此推薦使用 activity。
2. 設定載入中與載入失敗的圖片
Glide.with(context) .load(url) .placeholder(R.drawable.loading) //占位符 也就是加載中的圖片,可放個gif .error(R.drawable.failed) //失敗圖片 .into(view);
3. 加入圖片淡入效果
.crossFade()
4. 用 animate() 自訂動畫
第一種做法是從資源中載入動畫:傳入一個 Android 資源 id,也就是動畫的資源檔。最簡單的例子是系統內建的 slide-in-left(從左滑入)動畫 android.R.anim.slide_in_left,其 XML 描述如下:
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="https://schemas.android.com/apk/res/android"> <translate android:fromXDelta="-50%p" android:toXDelta="0" android:duration="@android:integer/config_mediumAnimTime"/> <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="@android:integer/config_mediumAnimTime" /> </set>
當然你也可以自訂 XML 動畫,例如一個「圖片從小放大到原尺寸」的縮放動畫:
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="https://schemas.android.com/apk/res/android" android:fillAfter="true"> <scale android:duration="@android:integer/config_longAnimTime" android:fromXScale="0.1" android:fromYScale="0.1" android:pivotX="50%" android:pivotY="50%" android:toXScale="1" android:toYScale="1"/> </set>
這兩個動畫都能套用到 Glide 的建造者中:
Glide .with( context ) .load( eatFoodyImages[0] ) .animate( android.R.anim.slide_in_left ) // or R.anim.zoom_in .into( imageView1 );
這樣,圖片從網路載入完成並準備好後,就會從左邊滑入。
透過自訂類別實作動畫
這其實很簡單,你只要實作 void animate(View view) 方法即可。這個 view 物件就是整個 target 視圖;若它是自訂視圖,你要先找到子元素再做動畫。以下是一個簡單的淡入動畫範例:
ViewPropertyAnimation.Animator animationObject = new ViewPropertyAnimation.Animator() { @Override public void animate(View view) { // if it's a custom view class, cast it here // then find subviews and do the animations // here, we just use the entire view for the fade animation view.setAlpha( 0f ); ObjectAnimator fadeAnim = ObjectAnimator.ofFloat( view, "alpha", 0f, 1f ); fadeAnim.setDuration( 2500 ); fadeAnim.start(); } }; 接著在 Glide 請求中設定這個動畫:
Glide .with( context ) .load( eatFoodyImages[1] ) .animate( animationObject ) .into( imageView2 );
在 animate(View view) 裡,你可以對視圖做任何想做的事,自由發揮即可。若要在自訂視圖中實作,只要建立這個物件,並在你的自訂方法裡呼叫。
5. 加入載入完成監聽
Glide.with(ShowImgActivity.this) .load(urlString) .centerCrop() .error(R.drawable.failed) .crossFade() .into(new GlideDrawableImageViewTarget(imageView) { @Override public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) { super.onResourceReady(drawable, anim); //在這裡添加一些圖片加載完成的操作 } )}; 6. 圖片緩存機制
Glide 預設同時開啟磁碟緩存與記憶體緩存,也能對單張圖片設定特定策略。
設定圖片不加入記憶體緩存:
Glide .with( context ) .load( eatFoodyImages[0] ) .skipMemoryCache( true ) .into( imageViewInternet );
設定圖片不加入磁碟緩存:
Glide .with( context ) .load( eatFoodyImages[0] ) .diskCacheStrategy( DiskCacheStrategy.NONE ) .into( imageViewInternet );
Glide 支援的磁碟緩存策略:
DiskCacheStrategy.NONE:不緩存圖片
DiskCacheStrategy.SOURCE:緩存圖片來源檔
DiskCacheStrategy.RESULT:緩存處理後的圖片
DiskCacheStrategy.ALL:緩存所有圖片(預設)
圖片載入優先級
Glide 也支援為圖片載入設定優先級,優先級高的先載入、低的後載入:
private void loadImageWithHighPriority() { Glide .with( context ) .load( UsageExampleListViewAdapter.eatFoodyImages[0] ) .priority( Priority.HIGH ) .into( imageViewHero ); } private void loadImagesWithLowPriority() { Glide .with( context ) .load( UsageExampleListViewAdapter.eatFoodyImages[1] ) .priority( Priority.LOW ) .into( imageViewLowPrioLeft ); Glide .with( context ) .load( UsageExampleListViewAdapter.eatFoodyImages[2] ) .priority( Priority.LOW ) .into( imageViewLowPrioRight ); } 7. 載入圓角/圓形圖片
/** * 圓形圖 * * Created by <lzh> on 2016/7/29. */ public class GlideCircleTransform extends BitmapTransformation { public GlideCircleTransform(Context context) { super(context); } @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { return circleCrop(pool, toTransform); } private static Bitmap circleCrop(BitmapPool pool, Bitmap source) { if (source == null) return null; int size = Math.min(source.getWidth(), source.getHeight()); int x = (source.getWidth() - size) / 2; int y = (source.getHeight() - size) / 2; // TODO this could be acquired from the pool too Bitmap squared = Bitmap.createBitmap(source, x, y, size, size); Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888); if (result == null) { result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(result); Paint paint = new Paint(); paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); paint.setAntiAlias(true); float r = size / 2f; canvas.drawCircle(r, r, r, paint); return result; } @Override public String getId() { return getClass().getName(); } } 使用時只要加上這句即可:.transform(new GlideCircleTransform(context))
Glide.with(mContext) .load(imageUrl) .transform(new GlideCircleTransform(mContext)) .into(holder.imageView);
注意事項:
不能直接替要使用 Glide 的 ImageView 設定 tag,因為 Glide 在載入圖片時內部會用到 tag,這樣做會造成衝突並報錯。若確實需要用 tag 寫邏輯,可以改用帶資源 id 的多個參數版本:
.setTag(R.string.xxx, xxx); 並以 .getTag(R.string.xxx); 取值。
以上就是本文的全部內容,希望對大家的學習有所幫助。
用 Android 打造一個簡單計算器
動手做一個計算器,是練習 Android 元件操作與事件處理的經典題目。本文分享的這個計算器雖然結構簡單,卻已能實現加、減、乘、除四則運算與連續運算,並針對小數運算做了優
Android Studio 1.0 穩定版完全攻略
Android Studio 1.0 發布2014 年 12 月 8 日,Google 正式發布 Android Studio 1.0 穩定版。它是一款針對 Androi
Android 進階:BroadcastReceiver 靜態與動態註冊實例詳解
前面幾篇分別談了 Activity 和 Service,這次輪到第三大組件 BroadcastReceiver。廣播是 Android 應用之間互通消息的機制,它和 In
Service 深入理解與實戰:Started、Bound 與 IntentService
把這部分學習的內容做個系統梳理。開頭先提一個容易踩的兼容性問題:Android 5.0 之後,啟動組件必須使用顯式 Intent;若沿用隱式寫法,需顯式指定包名,例如 i