SwiftUIでいこう!- スタンフォード大学Lecture 7: ViewModifier Animation - 2
カードの中に一部欠けた円形をパスを使って書きました。次にカードの中に表示されている絵文字を動かします。アニメーション については以下詳しく解説されているサイトがあります。
この講義ではText()にmodifireをつけて動かします。
基本的な動きは回転です。これは
.rotationEffect(Angle.degrees(card.isMatched ? 360 : 0))
とすれば良いのですが、これだけでは動きません。
.animation(Animation.linear(duration: 1).repeatForever(autoreverses:false))
これでアニメーション としてはぐるぐると回り始めます。条件は
card.isMatched
真の場合"360"でぐるっと回ります。疑の場合は"0"で動きません。
Text(card.content)
.rotationEffect(Angle.degrees(card.isMatched ? 360 : 0))
.animation(Animation.linear(duration: 1).repeatForever(autoreverses:false))
あと、絵文字フォントの調整をします。先に作っていた
private struct DrawingConstants{
static let fontScale:CGFloat = 0.7
static let fontSize:CGFloat = 32
を使い関数を作ります。
private func scale(thatFits size:CGSize)-> CGFloat{
min(size.width,size.height) / (DrawingConstants.fontSize / DrawingConstants.fontScale)
}
この関数を使って、
Text(card.content)
// 省略
.scaleEffect(scale(thatFits: geometry.size))
とします。GeometryReaderでサイズを取得して良い大きさに調整しています。
最終的なCardView()は以下となります。
struct CardView:View {
let card:EmojiGame.Card
var body: some View{
GeometryReader{ geometry in
ZStack{
Pie(startAngle: Angle(degrees: 0-90), endangle: Angle(degrees: 110-90))
.padding(5).opacity(0.5)
Text(card.content)
.rotationEffect(Angle.degrees(card.isMatched ? 360 : 0))
.animation(Animation.linear(duration: 1).repeatForever(autoreverses:false))
.scaleEffect(scale(thatFits: geometry.size))
}
.cardify(isFaceUp: card.isFaceUp)
}
}
この記事が気に入ったらサポートをしてみませんか?