SwiftUI — Animation動畫

自從接觸swiftUI動畫後覺得實在太好玩太有趣了!!今天想用簡單的例子跟大家分享😆

先建立需要手動點擊的畫面,定義了三個@State var 來建立狀態模型,初始值設為 false。圓與星形用ZStack來建立,將星形疊加在圓形上面。 使用onTapGesture偵測手勢。在 onTapGesture closure中,用 toggle() 來開啟狀態以改變View的外觀。

struct ContentView: View {

@State private var circleColorChange = false
@State private var starColorChange = false
@State private var starSizeChange = false

var body: some View {
ZStack {
Circle()
.frame(width: 200, height: 200)
.foregroundColor(circleColorChange ? Color(.systemBlue) : .black)

Image(systemName: "star.fill")
.foregroundColor(starColorChange ? .yellow : .red)
.scaleEffect(starSizeChange ? 7.0 : 5.0)
}
.onTapGesture {
self.circleColorChange.toggle()
self.starColorChange.toggle()
self.starSizeChange.toggle()
}
}
}

將程式以withAnimation包在onTapGesture中,呼叫withAnimation帶入參數為彈跳效果動畫。

withAnimation(.spring(response: 0.2, dampingFraction: 0.2, blendDuration: 0.2)) {
self.circleColorChange.toggle()
self.starColorChange.toggle()
self.starSizeChange.toggle()
}

若想嘗試不同的動畫效果還有以下幾種參數

  1. easeOut : 速度一開始快,然後越來越慢。
  2. easeIn : 速度一開始慢,然後越來越快。
  3. easeInOut : 速度一開始慢,然後越來越快,最後再越來越慢(.default 的動畫效果跟 easeInOut 類似)。
  4. linear : 維持固定的速度。
  5. spring : 彈跳動畫效果。

若想調整動畫時間可以在Animation中傳入參數duration。

詳細請參考:

--

--

LULU
彼得潘的 Swift iOS App 開發教室

Hi👋 I’m iOS developer, I hope I can grow with you guys ☺️ Let’s learn more together.