SlideShare a Scribd company logo
Hoc Tran, iOS Developer at Seven Peaks Software
SwiftUI Animation
The basic overview
An overview
Basic animation properties
• Positio
n

• Siz
e

• Angl
e

• Shap
e

• Colo
r

• Etc
Transformation
Translatio
n

PCircle().offset(x: isOn ? 100 : 0, y: 0)


Scalin
g

PCircle().scaleEffect(isOn ? 1.5 : 0.5)


Rotatio
n

PCircle().rotationEffect(isOn ? .init(degrees: 360) : .zero)


Opacit
y

PCircle().opacity(isOn ? 1.0 : 0.2)


Background colo
r

PCircle().background(isOn ? Color.gray : Color.white)
Timing functions
Text(“Linear")


PCircle()


.offset(x: isOn ? 100 : 0, y: 0)


.animation(.linear(duration: 2.0))


Text("EaseIn")


PCircle()


.offset(x: isOn ? 100 : 0, y: 0)


.animation(.easeIn(duration: 2.0))




Text("EaseOut")


PCircle()


.offset(x: isOn ? 100 : 0, y: 0)


.animation(.easeOut(duration: 2.0))


Text("EaseInOut")


PCircle()


.offset(x: isOn ? 100 : 0, y: 0)


.animation(.easeInOut(duration: 2.0))


Text("Spring")


PCircle()


.offset(x: isOn ? 100 : 0, y: 0)


.animation(


.spring(response: 0.5, dampingFraction: 0.5,
blendDuration: 0.5)


)
Animatable
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


}
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
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
Linus Torvalds
“Talk is cheap. Show me the code”
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
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?
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 }


}


}
Example
How to guide the SwiftUI to achieve a custom animation
Quiz
Af
fi
ne Transform
PCircle().transformEffect(isOn ?


CGAffineTransform.init(translationX: 100, y: 0)


: CGAffineTransform.identity


)


Button("Will it animate 🤔? Click me") {


withAnimation {


self.isOn.toggle()


}


}
GeometryEffect
GeometryEffect
public protocol GeometryEffect : Animatable, ViewModifier where Self.Body == Never {


/// Returns the current value of the effect.


func effectValue(size: CGSize) -> ProjectionTransform


}
GeometryEffect
Quiz resolving
struct AnimatableQuizEffect: GeometryEffect {


private (set) var dX: Double




var animatableData: Double {


get { dX }


set { dX = newValue }


}




func effectValue(size: CGSize) -> ProjectionTransform {


return ProjectionTransform(CGAffineTransform.init(translationX: CGFloat(dX), y: 0))


}


}


Animatable
GeometryEffect
GeometryEffect
Quiz resolving
PCircle()


.modifier(AnimatableQuizEffect(dX: isOn ? 100 : 0))




Button("It will animate 😉? Click me") {


withAnimation {


self.isOn.toggle()


}


}
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
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
AnimatableModifier
AnimatableModifier
public protocol AnimatableModifier : Animatable, ViewModifier {


}


public protocol Animatable {...}


public protocol ViewModifier {


func body(content: Self.Content) -> Self.Body


}
AnimatableModifier
A simple progress indicator
Circular
Sliding
20% 50% 75% 100%
Example
A simple progress indicator
struct PercentageModifier: AnimatableModifier {


...




private (set) var pct = 0.0




var animatableData: Double {


get { pct }


set { pct = newValue }


}




func body(content: Content) -> some View {


switch style {


case .sliding:


return AnyView(content.clipShape(SlidingShape(pct: pct)))


case .circular:


return AnyView(content.clipShape(CircularShape(pct: pct)))


}


}




private struct CircularShape: Shape {...}




private struct SlidingShape: Shape {...}


}
Animatable
ViewModi
fi
er
Circular progress Sliding progress
Example
A simple progress indicator
Circle()


.percentage(pct, style: .circular)


Image(systemName: "hand.thumbsup.fill")


.percentage(pct, style: .sliding)


Text("Happy New Year 🎉🎇🍾!")


.percentage(pct, style: .sliding)


Image(systemName: "thermometer")


.percentage(pct, style: .sliding)


Text("🎆")


.percentage(pct, style: .circular)


Rectangle()


.percentage(pct, style: .sliding)


.border(Color.yellow, width: 2)


.rotationEffect(Angle(degrees: 180))


Text("🦠")


.percentage(pct, style: .circular)
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 👨💻👩💻
Q&A
Animate like a boss!

More Related Content

PPT
Admissions in india 2015
KEY
Intro to Game Programming
PPTX
Intro to Canva
PDF
Real life XNA
PDF
SVGo workshop
DOCX
Computer graphics lab assignment
PDF
Computer graphics lab report with code in cpp
Admissions in india 2015
Intro to Game Programming
Intro to Canva
Real life XNA
SVGo workshop
Computer graphics lab assignment
Computer graphics lab report with code in cpp

What's hot (9)

PDF
Computer Graphics in Java and Scala - Part 1b
PDF
03 extensions
PPTX
2 d translation
PDF
110218 [아꿈사발표자료] taocp#1 1.2.9. 생성함수
PDF
Lesson 16: Derivatives of Logarithmic and Exponential Functions
PPTX
Dip 5 mathematical preliminaries
PPTX
Aaex2 group2
TXT
Variables
TXT
Variables
Computer Graphics in Java and Scala - Part 1b
03 extensions
2 d translation
110218 [아꿈사발표자료] taocp#1 1.2.9. 생성함수
Lesson 16: Derivatives of Logarithmic and Exponential Functions
Dip 5 mathematical preliminaries
Aaex2 group2
Variables
Variables
Ad

Similar to SwiftUI Animation - The basic overview (20)

PDF
UI Dynamics
PPTX
Animations & swift
PDF
A short guide to animations in iOS
PDF
Vamo a curvarno
PDF
Сергій Міськів, «SwiftUI: Animations»
KEY
Animation in iOS
PDF
Core Animation
PDF
animations
PDF
Building animated UI with Core Animation
PDF
[TECHCON 2019: MOBILE - iOS]5.사용자 경험을 높이는 애니메이션 만들기
PDF
Starting Core Animation
PDF
Александр Зимин – Анимация как средство самовыражения
PDF
Practical animation
PDF
Crafting interactions with Core Animations, David Ortinau
PDF
iOS Transition Animations The proper way to do it.pdf
PDF
iOS Core Animation
PDF
미려한 UI/UX를 위한 여정
PDF
MCE^3 - Marin Todorov - Building Swift Libraries for iOS
PDF
Quartz 2D with Swift 3
PDF
Minimizing Decision Fatigue to Improve Team Productivity
UI Dynamics
Animations & swift
A short guide to animations in iOS
Vamo a curvarno
Сергій Міськів, «SwiftUI: Animations»
Animation in iOS
Core Animation
animations
Building animated UI with Core Animation
[TECHCON 2019: MOBILE - iOS]5.사용자 경험을 높이는 애니메이션 만들기
Starting Core Animation
Александр Зимин – Анимация как средство самовыражения
Practical animation
Crafting interactions with Core Animations, David Ortinau
iOS Transition Animations The proper way to do it.pdf
iOS Core Animation
미려한 UI/UX를 위한 여정
MCE^3 - Marin Todorov - Building Swift Libraries for iOS
Quartz 2D with Swift 3
Minimizing Decision Fatigue to Improve Team Productivity
Ad

Recently uploaded (20)

PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
System and Network Administration Chapter 2
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
medical staffing services at VALiNTRY
PPTX
L1 - Introduction to python Backend.pptx
PDF
Digital Strategies for Manufacturing Companies
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
AI in Product Development-omnex systems
Operating system designcfffgfgggggggvggggggggg
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Upgrade and Innovation Strategies for SAP ERP Customers
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Navsoft: AI-Powered Business Solutions & Custom Software Development
System and Network Administration Chapter 2
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
How to Migrate SBCGlobal Email to Yahoo Easily
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
CHAPTER 2 - PM Management and IT Context
medical staffing services at VALiNTRY
L1 - Introduction to python Backend.pptx
Digital Strategies for Manufacturing Companies
ISO 45001 Occupational Health and Safety Management System
AI in Product Development-omnex systems

SwiftUI Animation - The basic overview

  • 1. Hoc Tran, iOS Developer at Seven Peaks Software SwiftUI Animation The basic overview
  • 3. Basic animation properties • Positio n • Siz e • Angl e • Shap e • Colo r • Etc
  • 4. Transformation Translatio n PCircle().offset(x: isOn ? 100 : 0, y: 0) Scalin g PCircle().scaleEffect(isOn ? 1.5 : 0.5) Rotatio n PCircle().rotationEffect(isOn ? .init(degrees: 360) : .zero) Opacit y PCircle().opacity(isOn ? 1.0 : 0.2) Background colo r PCircle().background(isOn ? Color.gray : Color.white)
  • 5. Timing functions Text(“Linear") PCircle() .offset(x: isOn ? 100 : 0, y: 0) .animation(.linear(duration: 2.0)) Text("EaseIn") PCircle() .offset(x: isOn ? 100 : 0, y: 0) .animation(.easeIn(duration: 2.0)) Text("EaseOut") PCircle() .offset(x: isOn ? 100 : 0, y: 0) .animation(.easeOut(duration: 2.0)) Text("EaseInOut") PCircle() .offset(x: isOn ? 100 : 0, y: 0) .animation(.easeInOut(duration: 2.0)) Text("Spring") PCircle() .offset(x: isOn ? 100 : 0, y: 0) .animation( .spring(response: 0.5, dampingFraction: 0.5, blendDuration: 0.5) )
  • 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
  • 10. Linus Torvalds “Talk is cheap. Show me the code”
  • 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 } } }
  • 14. Example How to guide the SwiftUI to achieve a custom animation
  • 15. Quiz Af fi ne Transform PCircle().transformEffect(isOn ? CGAffineTransform.init(translationX: 100, y: 0) : CGAffineTransform.identity ) Button("Will it animate 🤔? Click me") { withAnimation { self.isOn.toggle() } }
  • 17. GeometryEffect public protocol GeometryEffect : Animatable, ViewModifier where Self.Body == Never { /// Returns the current value of the effect. func effectValue(size: CGSize) -> ProjectionTransform }
  • 18. GeometryEffect Quiz resolving struct AnimatableQuizEffect: GeometryEffect { private (set) var dX: Double var animatableData: Double { get { dX } set { dX = newValue } } func effectValue(size: CGSize) -> ProjectionTransform { return ProjectionTransform(CGAffineTransform.init(translationX: CGFloat(dX), y: 0)) } } Animatable GeometryEffect
  • 19. GeometryEffect Quiz resolving PCircle() .modifier(AnimatableQuizEffect(dX: isOn ? 100 : 0)) Button("It will animate 😉? Click me") { withAnimation { self.isOn.toggle() } }
  • 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
  • 23. AnimatableModifier public protocol AnimatableModifier : Animatable, ViewModifier { } public protocol Animatable {...} public protocol ViewModifier { func body(content: Self.Content) -> Self.Body }
  • 24. AnimatableModifier A simple progress indicator Circular Sliding 20% 50% 75% 100%
  • 25. Example A simple progress indicator struct PercentageModifier: AnimatableModifier { ... private (set) var pct = 0.0 var animatableData: Double { get { pct } set { pct = newValue } } func body(content: Content) -> some View { switch style { case .sliding: return AnyView(content.clipShape(SlidingShape(pct: pct))) case .circular: return AnyView(content.clipShape(CircularShape(pct: pct))) } } private struct CircularShape: Shape {...} private struct SlidingShape: Shape {...} } Animatable ViewModi fi er Circular progress Sliding progress
  • 26. Example A simple progress indicator Circle() .percentage(pct, style: .circular) Image(systemName: "hand.thumbsup.fill") .percentage(pct, style: .sliding) Text("Happy New Year 🎉🎇🍾!") .percentage(pct, style: .sliding) Image(systemName: "thermometer") .percentage(pct, style: .sliding) Text("🎆") .percentage(pct, style: .circular) Rectangle() .percentage(pct, style: .sliding) .border(Color.yellow, width: 2) .rotationEffect(Angle(degrees: 180)) Text("🦠") .percentage(pct, style: .circular)
  • 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 👨💻👩💻