Android動畫使用之幀動畫

1. 前言

動畫在安卓中,使用是很是常見的,好比網絡請求時的loading,就是經過旋轉實現的。 在安卓中,動畫分爲兩大類, 分別是視圖動畫和屬性動畫。視圖動畫又分爲幀動畫和補間動畫。這篇文章主要講幀動畫的使用。三種動畫的使用文章地址以下:android

  1. 幀動畫
  2. 補間動畫
  3. 屬性動畫

2. 介紹

幀動畫,指的就是利用視覺停留的特色,把一張張靜態的圖片順序播放,造成動畫的效果。git


3. 使用

image

3.1 在drawable目錄建立xml文件,編寫好幀動畫的圖片集合
<?xml version="1.0" encoding="utf-8"?>

<animation-list
    android:oneshot="false"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/loading_1" android:duration="200"></item>
    <item android:drawable="@drawable/loading_2" android:duration="200"></item>
    <item android:drawable="@drawable/loading_3" android:duration="200"></item>
    <item android:drawable="@drawable/loading_4" android:duration="200"></item>
    <item android:drawable="@drawable/loading_5" android:duration="200"></item>
    <item android:drawable="@drawable/loading_6" android:duration="200"></item>
    <item android:drawable="@drawable/loading_7" android:duration="200"></item>
</animation-list>
複製代碼

解釋:
github

  • animation-list:圖片集合的根節點。
  • oneshot:是否只播放一次,true表示只會播放一次,false表示一直循環播放
  • item: 指定每一幀的 圖片(drawable="")和播放時間(duration="")
3.2 動畫的開啓和關閉
public class MainActivity extends BaseActivity {


    @BindView(R.id.iv)
    ImageView iv;

    AnimationDrawable animationDrawable = null;
    boolean isStart = false;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        // 獲取動畫對象
        animationDrawable = (AnimationDrawable) iv.getBackground();
    }

    
    @OnClick(R.id.iv)
    public void onViewClicked() {
        if (isStart) {
            stop();
        } else {
            start();
        }
    }

    //開啓動畫
    private void  start (){
        animationDrawable.start();
        isStart = true;
    }
    //關閉動畫
    private void  stop (){
        animationDrawable.stop();
        isStart = false;
    }
}
複製代碼

解釋:
bash

  • view.getBackground():獲取到動畫對象,在佈局文件中,給view的Background屬性指定了動畫資源。

4.總結
  • 準備好一連串的靜態圖片,在xml中定義好播放順序和時間
  • 把定義好的xml動畫文件設置給view的background屬性
  • 經過獲取的view的background獲取到動畫對象,調用start和stop方法來開啓或者關閉動畫。

5. 完整demo地址

6. 歷史文章目錄
相關文章
相關標籤/搜索