SlideShare uma empresa Scribd logo
1 de 28
Baixar para ler 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!

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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
 

Último

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
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.
 
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
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
(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
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 

Último (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
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...
 
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...
 
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...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
(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...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.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 👨💻👩💻