SlideShare a Scribd company logo
1 of 28
Download to read offline
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

What's hot

Computer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bComputer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bPhilip Schwarz
 
2 d translation
2 d translation2 d translation
2 d translationMani Kanth
 
110218 [아꿈사발표자료] taocp#1 1.2.9. 생성함수
110218 [아꿈사발표자료] taocp#1 1.2.9. 생성함수110218 [아꿈사발표자료] taocp#1 1.2.9. 생성함수
110218 [아꿈사발표자료] taocp#1 1.2.9. 생성함수Youngman Choe
 
Lesson 16: Derivatives of Logarithmic and Exponential Functions
Lesson 16: Derivatives of Logarithmic and Exponential FunctionsLesson 16: Derivatives of Logarithmic and Exponential Functions
Lesson 16: Derivatives of Logarithmic and Exponential FunctionsMatthew Leingang
 
Dip 5 mathematical preliminaries
Dip 5 mathematical preliminariesDip 5 mathematical preliminaries
Dip 5 mathematical preliminariesManas Mantri
 

What's hot (9)

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

Similar to SwiftUI Animation - The basic overview

Intro to Python (High School) Unit #3
Intro to Python (High School) Unit #3Intro to Python (High School) Unit #3
Intro to Python (High School) Unit #3Jay Coskey
 
CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations Rob LaPlaca
 
openFrameworks 007 - graphics
openFrameworks 007 - graphicsopenFrameworks 007 - graphics
openFrameworks 007 - graphicsroxlu
 
ScalaDays 2014 - Reactive Scala 3D Game Engine
ScalaDays 2014 - Reactive Scala 3D Game Engine ScalaDays 2014 - Reactive Scala 3D Game Engine
ScalaDays 2014 - Reactive Scala 3D Game Engine Aleksandar Prokopec
 
Introduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User GroupIntroduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User Groupdreambreeze
 
Introduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User GroupIntroduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User Groupbernice-chan
 
The Ring programming language version 1.5.4 book - Part 60 of 185
The Ring programming language version 1.5.4 book - Part 60 of 185The Ring programming language version 1.5.4 book - Part 60 of 185
The Ring programming language version 1.5.4 book - Part 60 of 185Mahmoud Samir Fayed
 
CS 354 Object Viewing and Representation
CS 354 Object Viewing and RepresentationCS 354 Object Viewing and Representation
CS 354 Object Viewing and RepresentationMark Kilgard
 
The Ring programming language version 1.6 book - Part 62 of 189
The Ring programming language version 1.6 book - Part 62 of 189The Ring programming language version 1.6 book - Part 62 of 189
The Ring programming language version 1.6 book - Part 62 of 189Mahmoud Samir Fayed
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05cKaz Yoshikawa
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manualUma mohan
 
Enhancing UI/UX using Java animations
Enhancing UI/UX using Java animationsEnhancing UI/UX using Java animations
Enhancing UI/UX using Java animationsNaman Dwivedi
 
CG OpenGL Shadows + Light + Texture -course 10
CG OpenGL Shadows + Light + Texture -course 10CG OpenGL Shadows + Light + Texture -course 10
CG OpenGL Shadows + Light + Texture -course 10fungfung Chen
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonAlex Payne
 
Александр Зимин – Анимация как средство самовыражения
Александр Зимин – Анимация как средство самовыраженияАлександр Зимин – Анимация как средство самовыражения
Александр Зимин – Анимация как средство самовыраженияCocoaHeads
 
Computer vision image enhancement ppt prajwal deshmukh
Computer vision image enhancement ppt prajwal deshmukhComputer vision image enhancement ppt prajwal deshmukh
Computer vision image enhancement ppt prajwal deshmukhprajdesh26
 
Html5 canvas
Html5 canvasHtml5 canvas
Html5 canvasGary Yeh
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf ChicagoJanie Clayton
 

Similar to SwiftUI Animation - The basic overview (20)

Intro to Python (High School) Unit #3
Intro to Python (High School) Unit #3Intro to Python (High School) Unit #3
Intro to Python (High School) Unit #3
 
CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations
 
openFrameworks 007 - graphics
openFrameworks 007 - graphicsopenFrameworks 007 - graphics
openFrameworks 007 - graphics
 
ScalaDays 2014 - Reactive Scala 3D Game Engine
ScalaDays 2014 - Reactive Scala 3D Game Engine ScalaDays 2014 - Reactive Scala 3D Game Engine
ScalaDays 2014 - Reactive Scala 3D Game Engine
 
Raphaël
RaphaëlRaphaël
Raphaël
 
Introduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User GroupIntroduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User Group
 
Introduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User GroupIntroduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User Group
 
The Ring programming language version 1.5.4 book - Part 60 of 185
The Ring programming language version 1.5.4 book - Part 60 of 185The Ring programming language version 1.5.4 book - Part 60 of 185
The Ring programming language version 1.5.4 book - Part 60 of 185
 
CS 354 Object Viewing and Representation
CS 354 Object Viewing and RepresentationCS 354 Object Viewing and Representation
CS 354 Object Viewing and Representation
 
The Ring programming language version 1.6 book - Part 62 of 189
The Ring programming language version 1.6 book - Part 62 of 189The Ring programming language version 1.6 book - Part 62 of 189
The Ring programming language version 1.6 book - Part 62 of 189
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
Enhancing UI/UX using Java animations
Enhancing UI/UX using Java animationsEnhancing UI/UX using Java animations
Enhancing UI/UX using Java animations
 
CG OpenGL Shadows + Light + Texture -course 10
CG OpenGL Shadows + Light + Texture -course 10CG OpenGL Shadows + Light + Texture -course 10
CG OpenGL Shadows + Light + Texture -course 10
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
Александр Зимин – Анимация как средство самовыражения
Александр Зимин – Анимация как средство самовыраженияАлександр Зимин – Анимация как средство самовыражения
Александр Зимин – Анимация как средство самовыражения
 
Computer vision image enhancement ppt prajwal deshmukh
Computer vision image enhancement ppt prajwal deshmukhComputer vision image enhancement ppt prajwal deshmukh
Computer vision image enhancement ppt prajwal deshmukh
 
Html5 canvas
Html5 canvasHtml5 canvas
Html5 canvas
 
Monadologie
MonadologieMonadologie
Monadologie
 
3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago
 

Recently uploaded

Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 

Recently uploaded (20)

Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 

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 👨💻👩💻