iT邦幫忙

2021 iThome 鐵人賽

DAY 18
1
自我挑戰組

社畜轉行之旅,30天Kotlin學習筆記系列 第 18

Day 18 | Frame Animation

逐格動畫Frame Animation

最早期的動畫製作方式,使用不同的圖片連續撥放

  1. 先將圖片放入專案,並在drawable下建立一個XML檔,定義圖片集合,並把圖片依序放置於集合中。

    <?xml version ="1.0" encoding ="utf-8"?><!--  Learn More about how to use App Actions: https://developer.android.com/guide/actions/index.html -->
    <animation-list
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:oneshot="false">
        <item
            android:drawable="@drawable/food1"
            android:duration="200"/>
        <item
            android:drawable="@drawable/food2"
            android:duration="200"/>
        <item
            android:drawable="@drawable/food3"
            android:duration="200"/>
    </animation-list>
    
    • oneshot屬性的參數類型為Boolean,控制動畫要不要循環播放,若為false則連續執行動畫。
    • duration屬性的參數類型為Integer,以毫秒控制圖片持續時間
  2. 啟用動畫

    package com.example.lab10
    
    import android.graphics.drawable.AnimationDrawable
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.widget.Button
    import android.widget.ImageView
    
    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            //教科書上沒有這句,但我編譯器過不了我還是自己加了XD
            val img_loading = findViewById<ImageView>(R.id.img_loading)
            //將動畫的drawable指定為ImageView的背景資源
            img_loading.setBackgroundResource(R.drawable.frame_animation)
            findViewById<Button>(R.id.btn_start).setOnClickListener{
                //將圖片背景轉為AnimationDrawable類別並執行
                val animation = img_loading.background as AnimationDrawable
                animation.start()
            }
            findViewById<Button>(R.id.btn_stop).setOnClickListener{
                //將圖片背景轉為AnimationDrawable類別並停止
                val animation = img_loading.background as AnimationDrawable
                animation.stop()
            }
        }
    }
    

    這個動畫實作踩了一個坑是,我先建立了XML檔,但不知道是不是建立方式錯誤,他一直從drawable跑到xml資料夾去,搞到後來我抓狂,直接從MainActivity中對著frame_animation按Alt+Enter,讓IDE幫我生一個XML出來,才成功運行。


上一篇
Day 17 | 今天是Coroutiones的 Dispatcher
下一篇
Day 19 | 補間動畫
系列文
社畜轉行之旅,30天Kotlin學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言