編輯:關於 Android 程式設計
GIF 在網頁開發裡隨處可見,很多動畫效果不必再寫程式碼就能呈現,App 中的使用也越來越多。但 Android SDK 並沒有現成的 GifView,因此只能自己打造一個 View。
好消息是 SDK 提供了 Movie 這個類別,它是實作 GifView 的關鍵:一個方法依播放時間決定目前該顯示哪一幀,另一個方法把該幀繪製到畫布上。兩者搭配就能完成播放。

點擊暫停按鈕後,動畫會停在當前幀。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="gifCommon">
<attr name="gif_src" format="reference" />
<attr name="decode_stream" format="boolean" />
<attr name="default_animation_time" format="integer" />
</declare-styleable>
</resources>
三個屬性分別對應:GIF 資源、是否以串流方式解碼、以及 GIF 本身未提供時長資訊時的預設循環間隔。
public class GifView extends View {
private Movie mMovie;
/** 動畫起始時間 */
private long mMovieStart;
private boolean mPaused = false;
/** 目前幀對應的時間點 */
private int mCurrentAnimationTime;
private boolean decodeStream;
private int srcId;
private int defaultTime;
public GifView(Context context) {
this(context, null);
}
public GifView(Context context, AttributeSet set) {
super(context, set);
init(context, set);
}
private void init(Context context, AttributeSet set) {
TypedArray a = context.obtainStyledAttributes(set, R.styleable.gifCommon);
srcId = a.getResourceId(R.styleable.gifCommon_gif_src, -1);
decodeStream = a.getBoolean(R.styleable.gifCommon_decode_stream, true);
defaultTime = a.getInteger(R.styleable.gifCommon_default_animation_time, 1000);
a.recycle();
setFocusable(true);
InputStream is = context.getResources().openRawResource(srcId);
if (decodeStream) {
mMovie = Movie.decodeStream(is);
} else {
mMovie = Movie.decodeByteArray(streamToBytes(is), 0,
streamToBytes(is).length);
}
}
@Override
protected void onDraw(Canvas canvas) {
if (mMovie == null) return;
if (!mPaused) {
updateAnimationTime();
drawMovieFrame(canvas);
invalidate(); // 持續驅動下一幀
} else {
drawMovieFrame(canvas); // 暫停時只畫當前幀
}
}
private void updateAnimationTime() {
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) {
mMovieStart = now;
}
int dur = mMovie.duration();
if (dur == 0) {
dur = defaultTime;
}
mCurrentAnimationTime = (int) ((now - mMovieStart) % dur);
}
private void drawMovieFrame(Canvas canvas) {
mMovie.setTime(mCurrentAnimationTime);
canvas.save(Canvas.MATRIX_SAVE_FLAG);
mMovie.draw(canvas, 0, 0);
canvas.restore();
}
/** 控制暫停與續播 */
public void setPaused(boolean paused) {
this.mPaused = paused;
if (!paused) {
// 續播時重算起點,避免動畫跳格
mMovieStart = android.os.SystemClock.uptimeMillis() - mCurrentAnimationTime;
}
invalidate();
}
public boolean isPaused() {
return mPaused;
}
/** 讓自訂 View 支援 wrap_content */
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width, height;
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else {
int desired = (int) (getPaddingLeft() + mMovie.width() + getPaddingRight());
width = Math.min(desired, widthSize);
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else {
int desired = (int) (getPaddingTop() + mMovie.height() + getPaddingBottom());
height = Math.min(desired, heightSize);
}
setMeasuredDimension(width, height);
}
/** 串流轉位元組陣列 */
private static byte[] streamToBytes(InputStream is) {
ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int len;
try {
while ((len = is.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
} catch (IOException e) {
Log.e("GifView", "讀取串流失敗", e);
}
return os.toByteArray();
}
}
用法與一般 View 無異,記得加上自訂命名空間:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:gif="https://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fed952"
android:gravity="center">
<view.GifView
android:id="@+id/gif_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffffff"
gif:decode_stream="true"
gif:default_animation_time="1000"
gif:gif_src="@drawable/animated_gif" />
<TextView
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/gif_view"
android:text="暫停" />
</RelativeLayout>
(now - start) % duration 讓動畫自動無限循環。
VoLTE 高清語音通話支持哪些手機?機型清單一次看
隨著蘋果向 iPhone 6 以上機型推送 VoLTE 高清語音通話的運營商配置更新,越來越多網友開始關注這項新的語音技術。那麼目前國內有哪些手機支持 VoLTE 高清語
走進絢爛多彩的屬性動畫 Property Animation(上篇)
1. 屬性動畫概述 動畫是 App 增強交互與用戶體驗的重要一環,尤其在提示或引導場景中,合理的動畫能帶來更愉悅的使用感受。早期 Android 版本動畫機制並不完善:補
自製仿 MIUI 風格 ViewPagerIndicator:Tab 與頁面滑動聯動的完整實作
一、要做什麼 做過 Tab 切換的人大概都用過 TabPageIndicator,許多知名 App 也採用這個開源指示器。但你有沒有想過自己動手做一個?究竟有多複雜?這篇
Android 開發第六彈:動手做一個簡易時鐘與計時器
接續上一篇的簡易時鐘(鬧鐘)。這次做時鐘與計時器,外觀一樣樸素,但功能齊全。 時鐘 先從最簡單的時鐘開始。顯示目前時間而已,若要換成世界各城市的時間,也只是在小時上加减