Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 逐幀播放多張圖片實現動畫效果

Android 支持逐幀(frame-by-frame)播放圖片來形成動態效果。做法很簡單:準備好若干張連續的圖片放入 res/drawable,在 res 下新建 anim 文件夾並寫一個 animation-list 描述文件,最後交由 ImageView 播放。

第一步:新建 res/anim/animation_list.xml

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="https://schemas.android.com/apk/res/android"
    android:oneshot="true">
    <item android:drawable="@drawable/c1" android:duration="200" />
    <item android:drawable="@drawable/c2" android:duration="200" />
    <item android:drawable="@drawable/c3" android:duration="200" />
    <item android:drawable="@drawable/c4" android:duration="200" />
    <item android:drawable="@drawable/c5" android:duration="200" />
    <item android:drawable="@drawable/c6" android:duration="200" />
</animation-list>

其中 c1 到 c6 是加入的圖片名稱,duration 是每幀停留的毫秒數,這裡每幀 200 毫秒即 5 幀每秒。android:oneshot="true" 表示只播放一次,設為 false 則循環播放。

第二步:在布局中放置 ImageView

在窗體布局裡放一個 ImageView 控件,並在代碼中取得引用:

_imageView1 = (ImageView) findViewById(R.id.imageView1);

第三步:加載並啟動動畫

// 設置動畫背景
_imageView1.setBackgroundResource(R.anim.animation_list);
// 其中 R.anim.animation_list 就是上一步準備的描述文件資源名

// 獲得動畫對象
_animaition = (AnimationDrawable) _imageView1.getBackground();

// 是否僅僅啟動一次?
_animaition.setOneShot(false);

if (_animaition.isRunning()) { // 是否正在運行?
    _animaition.stop();        // 停止
}
_animaition.start();           // 啟動

關鍵點在於 AnimationDrawable 必須從 ImageView 的 background 中取得,因此描述文件要用 setBackgroundResource() 而不是 setImageResource() 加載。另外,逐幀動畫會一次性把全部幀解碼進內存,圖片過大或幀數過多時容易引發 OutOfMemoryError,實際項目中建議控制單幀尺寸,或改用合適的圖片加載方案。

Copyright © Linux教程網 All Rights Reserved