7. Animatable
/// A type that describes how to animate a property of a view.
public protocol Animatable {
/// The type de
fi
ning the data to animate.
associatedtype AnimatableData : VectorArithmetic
/// The data to animate.
var animatableData: Self.AnimatableData { get set }
}
extension Animatable where Self : VectorArithmetic {
/// The data to animate.
public var animatableData: Self
}
8. VectorArithmetic
Confirm AdditiveArithmeti
c
Scalar multiplicatio
n
public protocol VectorArithmetic : AdditiveArithmetic {
/// Multiplies each component of this value by the given value.
mutating func scale(by rhs: Double)
/// Returns the dot-product of this vector arithmetic instance with
itself.
var magnitudeSquared: Double { get }
}
let from = 0.0
let to = 1.0
[0.0, 0.2, 0.4, 0.6, 0.8, 1.0].forEach {
var range = (to - from)
range.scale(by: $0)
let opacity = range + from
img.opacity(opacity)
}
0.0 0.2 0.4 0.6 0.8 1.0
How the animation works
9. Animatable
Animatable
• Angl
e
• Capsul
e
• RoundedRectangl
e
• ScaledShap
e
• StrokeStyl
e
• TransformedShap
e
• etc
VectorArithmeti
c
• AnimatablePai
r
• CGFloa
t
• Doubl
e
• EmptyAnimatableDat
a
• Floa
t
Default conformation
11. Example
How to guide the SwiftUI to achieve a
struct Star: Shape {
let edges: Int
func path(in rect: CGRect) -> Path {
let angleStep = Angle(degrees: 360 / Double(edges))
return starPath(steps: edges, angleStep: angleStep, rect: rect)
}
}
5 edges 10 edges 100 edges
12. Example
How to guide the SwiftUI to achieve a
Star(edges: edges)
.stroke(Color.purple, lineWidth: 5)
.frame(width: 300, height: 300)
Picker("# edges (edges)",
selection: $edges.animation(.easeInOut)) {
Text("5").tag(5)
Text("10").tag(10)
Text(“100").tag(100)
}
Whyyyyyyyyyyyyyyy?
13. Example
How to guide the SwiftUI to achieve a
struct AnimatableStar: Shape {
private var edges: Double
init(edges: Int) {
self.edges = Double(edges)
}
func path(in rect: CGRect) -> Path {
var n = Int(edges)
if edges > Double(Int(edges)) {
n += 1
}
let angleStep = Angle(degrees: 360 / edges)
return starPath(steps: n, angleStep: angleStep, rect: rect)
}
var animatableData: Double {
set { edges = newValue }
get { return edges }
}
}
17. GeometryEffect
public protocol GeometryEffect : Animatable, ViewModifier where Self.Body == Never {
/// Returns the current value of the effect.
func effectValue(size: CGSize) -> ProjectionTransform
}
20. Math behind the transformation
Translation
Scaling
Rotation
General
Consequenc
e
The concatenation is NOT commutative
.
•Rotation x Scaling ≠ Scaling x Rotatio
n
•Translation x Rotation ≠ Rotation x Translatio
n
•Et
c
21. Math behind the transformation
Consequenc
e
The concatenation is NOT commutative
.
•Rotation x Scaling ≠ Scaling x Rotatio
n
•Translation x Rotation ≠ Rotation x Translatio
n
•Et
c
27. Conclusion
The effective way to implement animation
?
Animate like a boss!
https://github.com/7-peaks-software/iOS-Meetup-10.02.21 👈
Eat more vegetable 🍠🥑🍓🥗
Happy coding 👨💻👩💻