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

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 1b
Philip Schwarz
 
03 extensions
03 extensions03 extensions
03 extensions
Hadley Wickham
 
2 d translation
2 d translation2 d translation
2 d translation
Mani 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 Functions
Matthew Leingang
 
Dip 5 mathematical preliminaries
Dip 5 mathematical preliminariesDip 5 mathematical preliminaries
Dip 5 mathematical preliminaries
Manas Mantri
 
Aaex2 group2
Aaex2 group2Aaex2 group2
Aaex2 group2
Shiang-Yun Yang
 
Variables
VariablesVariables
Variables
mircea_v20
 
Variables
VariablesVariables
Variables
David Frias
 

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 #3
Jay 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 - graphics
roxlu
 
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
 
Raphaël
RaphaëlRaphaë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
bernice-chan
 
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
dreambreeze
 
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
Mahmoud Samir Fayed
 
CS 354 Object Viewing and Representation
CS 354 Object Viewing and RepresentationCS 354 Object Viewing and Representation
CS 354 Object Viewing and Representation
Mark 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 189
Mahmoud Samir Fayed
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
Kaz Yoshikawa
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
Uma mohan
 
Enhancing UI/UX using Java animations
Enhancing UI/UX using Java animationsEnhancing UI/UX using Java animations
Enhancing UI/UX using Java animations
Naman 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 10
fungfung 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 Horizon
Alex 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 deshmukh
prajdesh26
 
Html5 canvas
Html5 canvasHtml5 canvas
Html5 canvas
Gary Yeh
 
Monadologie
MonadologieMonadologie
Monadologie
league
 
3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago
Janie 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

How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
campbellclarkson
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
vaishalijagtap12
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
Luigi Fugaro
 
How GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdfHow GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdf
Zycus
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
Jhone kinadey
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio, Inc.
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Peter Caitens
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
kalichargn70th171
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
widenerjobeyrl638
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
kgyxske
 

Recently uploaded (20)

How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
 
bgiolcb
bgiolcbbgiolcb
bgiolcb
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
 
How GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdfHow GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdf
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
 

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