| 方案 | 優點 | 缺點 |
|---|---|---|
| 拆幀存 PNG + AnimationDrawable | 播放流暢、無解碼開銷 | APK 體積暴增、維護麻煩 |
| 原生 Movie 類 | 代碼極少 | 不支援所有 GIF 特性、無法控制播放速度 |
| 自訂解碼 View (本文方案) | 體積小、可控播放、支援暫停/速度調節 | 需自行處理解碼效能 |
Bitmap 與延遲時間。postInvalidate() 觸發重繪。gif_src、gif_delay、gif_auto_start。public class GifView extends View implements Runnable {
private GifDecoder mDecoder;
private boolean mIsPlaying = false;
private int mSpeedFactor = 1; // 播放速度倍率
private Bitmap mCurrentFrame;
// 建構子:支援 XML 屬性
public GifView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.GifView);
int resId = a.getResourceId(R.styleable.GifView_gif_src, 0);
int delay = a.getInt(R.styleable.GifView_gif_delay, 1);
boolean autoStart = a.getBoolean(R.styleable.GifView_gif_auto_start, false);
a.recycle();
if (resId != 0) setGifResource(resId);
mSpeedFactor = delay;
if (autoStart) start();
}
/** 設定 GIF 資源 */
public void setGifResource(@RawRes int resId) {
mDecoder = new GifDecoder();
mDecoder.read(getResources().openRawResource(resId));
mCurrentFrame = mDecoder.getNextFrame();
requestLayout(); // 觸發 onMeasure
}
/** 開始播放 */
public void start() {
if (mIsPlaying) return;
mIsPlaying = true;
new Thread(this).start();
}
/** 暫停播放 */
public void stop() {
mIsPlaying = false;
}
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
if (mDecoder != null) {
setMeasuredDimension(
resolveSize(mDecoder.getWidth(), widthSpec),
resolveSize(mDecoder.getHeight(), heightSpec));
} else {
super.onMeasure(widthSpec, heightSpec);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mCurrentFrame != null) {
canvas.drawBitmap(mCurrentFrame, 0, 0, null);
}
}
@Override
public void run() {
while (mIsPlaying && mDecoder != null) {
try {
// 取得下一幀與延遲
mCurrentFrame = mDecoder.getNextFrame();
int delay = mDecoder.getNextDelay() / mSpeedFactor;
// 切換到主執行緒重繪
postInvalidate();
Thread.sleep(Math.max(10, delay)); // 防止過快
} catch (Exception e) {
Log.w("GifView", "播放異常", e);
break;
}
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
stop(); // 防止洩漏
}
}
<resources>
<declare-styleable name="GifView">
<attr name="gif_src" format="reference" />
<attr name="gif_delay" format="integer" />
<attr name="gif_auto_start" format="boolean" />
</declare-styleable>
</resources>
XML
<com.example.widget.GifView
android:id="@+id/gif_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:gif_src="@raw/loading"
app:gif_auto_start="true" />
代碼控制
GifView gifView = findViewById(R.id.gif_view);
Button btnStart = findViewById(R.id.btn_start);
Button btnStop = findViewById(R.id.btn_stop);
btnStart.setOnClickListener(v -> gifView.start());
btnStop.setOnClickListener(v -> gifView.stop());
GifDecoder 內部使用 BitmapFactory.Options.inMutable=true + inBitmap 複用記憶體,避免頻繁 GC。run() 中每 N 幀才 postInvalidate()。drawBitmap 會走 GPU 路徑。完整解碼器代碼較長(約 300 行),核心流程:
建議參考開源實現:android-gif-drawable (JNI 版,效能最佳) 或 Java 純解碼版。