1. 程式人生 > >Android三種動畫之(一)幀動畫

Android三種動畫之(一)幀動畫

幀動畫介紹:就是將原有的照片一幀一幀的排列好按照一定的順序播放而達到動畫的效果

技術實現:實現的方式有兩種,一種是在資原始檔中新增圖片,一種是直接在程式碼中新增圖片

第一種:在資原始檔中新增圖片

1.在drawable裡面新建檔案frame_animation.xml 

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">

    <!--其中 android:oneshot="false" 是表示不迴圈一次,true代表的是隻迴圈一次-->
    <!--其中 android:drawable="@mipmap/zhen1" 代表的是新增資原始檔-->
    <!--其中 android:duration="100" 代表的是這幀照片停留的時間是多少時間,單位毫秒-->

    <item
        android:drawable="@mipmap/zhen1"
        android:duration="100" />
    <item
        android:drawable="@mipmap/zhen2"
        android:duration="100" />
    <item
        android:drawable="@mipmap/zhen3"
        android:duration="100" />
    <item
        android:drawable="@mipmap/zhen4"
        android:duration="200" />
    <item
        android:drawable="@mipmap/zhen5"
        android:duration="200" />
    <item
        android:drawable="@mipmap/zhen6"
        android:duration="200" />

</animation-list>

然後在佈局裡面的ImageView呼叫

        <ImageView
            android:id="@+id/iv_frame"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="10dp"
            android:src="@drawable/frame_animation" />

最後在程式碼裡面使用這個動畫:

        mIvFrame.setImageResource(R.drawable.frameanimation);
        animationDrawable = (AnimationDrawable) mIvFrame.getDrawable();
        animationDrawable.start();

另外還有其他的設定:

animationDrawable.setOneShot(true);//在程式碼裡設定是否迴圈播放
android:oneshot="false"//在資原始檔裡面設定是否迴圈播放,false代表是
animationDrawable.isRunning();//是否正在播放
animationDrawable.start();//表示開始動畫
animationDrawable.stop();//表示停止動畫,分別在需要的點選事件裡面呼叫

第二種:在程式碼中新增資源圖片

animationDrawable = new AnimationDrawable();
animationDrawable.addFrame(getResources().getDrawable(R.mipmap.zhen1),200);//新增圖片
animationDrawable.addFrame(getResources().getDrawable(R.mipmap.zhen2),200);
animationDrawable.addFrame(getResources().getDrawable(R.mipmap.zhen3),200);
animationDrawable.addFrame(getResources().getDrawable(R.mipmap.zhen4),200);
animationDrawable.addFrame(getResources().getDrawable(R.mipmap.zhen5),200);
animationDrawable.addFrame(getResources().getDrawable(R.mipmap.zhen6),200);
animationDrawable.setOneShot(false);//是否迴圈播放
mIvFrame.setBackground(animationDrawable);
animationDrawable.start();

如果要新增資原始檔太多的話可以迴圈新增:

     animationDrawable = new AnimationDrawable();
     for (int i = 1; i <= 6; i++) {
         int id = getResources().getIdentifier("zhen" + i, "mipmap", getPackageName());
         Drawable drawable = getResources().getDrawable(id);
         animationDrawable.addFrame(drawable, 200);
     }
     animationDrawable.setOneShot(false);
     mIvFrame.setImageDrawable(animationDrawable);
     animationDrawable.start();

下載地址:https://download.csdn.net/download/lanrenxiaowen/10753851