# CS193P - Lecture 8: Animation Demonstration - 70 mins ## 00:34 shuffle button ```swift= // view model 新增一個 intent function func shuffle() { model.shuffle() } ``` ```swift= // model 對應,且在初始化時也打亂 mutating func shuffle() { cards.shuffle() } init(...) { ... cards.shuffle() } ``` ```swift= // view var shuffle: some View { Button("Shuffle") { withAnimation { game.shuffle() } } } var body: some View { ZStack(alignment: .bottom) { VStack { gameBody HStack { restart Spacer() shuffle } .padding(.horizontal) } } .padding() } ``` ViewModifier -> AnimatableModifier var animatableData: Double ~27:40 recap 我們已經做了哪一些事情 ~29:06 配對完成的卡片,在第三張卡片被掀開時,有 fade out 動畫,那就是 transition animation ~36:25 ```swift= AspectVGrid(...) { } .onAppear { // "deal" cards } @State var dealt = Set<Int>() ``` ~43:08 var deckBodyn ## 1:08:07 Pie timer animation ## 1:21:47 recap 1. matchedGeometryEffect (牌從牌堆發牌) 2. our special ViewModifier (card flipping) 3. implicit animation (match後自轉) 4. explicit animation (shuffle button) 5. onAppear 後 pie graph bonus time 6. delayed dealing (逐張發牌的動畫) --- #### (1)matchedGeometryEffect view 不局限於在同一個 container 底下的位置移動 deckBody 移動到 gameBody #### (2)our special ViewModifier - ViewModifier 無法做到動畫的那種兩個離散數值之間的平滑變化 - 所以改用 AnimatableModifier - AnimatableModifier 有 animatableData 可以讓我們做到這件事 ```swift= struct Cardify: AnimatableModifier { init(isFaceUp: Bool) { rotation = isFaceUp ? 0 : 180 } var animatableData: Double { get { rotation } set { rotation = newValue } } var rotation: Double // in degrees func body(content: Content) -> some View { ZStack { let shape = RoundedRectangle(cornerRadius: DrawingConstants.cornerRadius) if rotation < 90 { ... } else { ... } content.opacity(rotation < 90 ? 1 : 0) } .rotation3DEffect(Angle.degrees(rotation), axis: (0, 1, 0)) } } ``` #### (3)implicit animation (card.isMatched == true) -> 自轉 ```swift= Text(card.content) .padding(DrawingConstants.circlePadding) .rotationEffect(Angle.degrees(card.isMatched ? 360 : 0)) .animation(Animation.linear(duration: 1).repeatForever(autoreverses: false)) ``` #### (4)explicit animation withAnimation { ... } ```swift= Button("Shuffle") { withAnimation { game.shuffle() } } ``` #### (5)onAppear 後 pie graph bonus time @State private var animatedBonusRemaining: Double = 0 #### (6)delayed dealing (逐張發牌的動畫) ```swift= var deckBody: some View { ZStack { ForEach(game.cards.filter(isUndealt)) { card in CardView(card: card) ... } } .onTapGesture { for card in game.cards { withAnimation(dealAnimation(for: card)) { deal(card) } } } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up