SlideShare a Scribd company logo
Building animated UI with
Core Animation
Marco Zoffoli
iOS Developer
Agenda
• What is Core Animation?
• Layers
• Animating layer properties
• Transactions
• 3D transforms
• Advanced layer effects
• Performance tips & tricks

2 /50
Agenda
• What is Core Animation?
• Layers
• Animating layer properties
• Transactions
• 3D transforms
• Advanced layer effects
• Performance tips & tricks

3 /50
What is Core Animation?
• Core Animation is an animation framework for animating UI
elements and creating visual effects

• Available on both iOS and Mac OS X (we’ll cover only iOS)
• Just provide a few parameters and Core Animation will do
the rest:

• Starting point
• Ending point
• Timing

4 /50
Architecture

UIKit
Core Animation
OpenGL ES

Core Graphics
GPU

5 /50
Agenda
• What is Core Animation?
• Layers
• Animating layer properties
• Transactions
• 3D transforms
• Advanced layer effects
• Performance tips & tricks

6 /50
CALayer
• A layer represents a rectangular portion of the screen with
visual contents

• Every UIView has a CALayer, accessible via view.layer
• drawRect: actually draws into the backing layer

• Model similar to UIView:
• addSublayer:
• setNeedsDisplay
• layoutSublayers
• drawInContext:

• ...
7 /50
CALayer geometry
x
y
layer.position = CGPointMake(150, 200)

layer.bounds = CGRectMake(0, 0, 170, 220)
layer.transform =
CATransform3DMakeRotation(M_PI / 4, 0, 0, 1)

+

r
ye

la
superlayer

8 /50
CALayer geometry

layer.anchorPoint = CGPointMake(0.5, 1)

layer.transform =
CATransform3DMakeRotation(M_PI / 4, 0, 0, 1)
ye

la

+

r
superlayer

y
la
er
9 /50
CALayer appearance
layer.cornerRadius = 5.0;

layer.borderWidth = 2.0;
layer.borderColor = [UIColor redColor].CGColor;

layer.shadowOpacity = 0.7;
layer.shadowRadius = 5.0;
layer.shadowOffset = CGSizeMake(1, 1);
layer.shadowColor = [UIColor blackColor].CGColor;

layer.mask = maskLayer;
superlayer

10 /50
CALayer class hierarchy
CALayer

CAEmitterLayer

CAShapeLayer

CAGradientLayer

CATextLayer

CAReplicatorLayer

CATiledLayer

CAScrollLayer

CATransformLayer

11 /50
Agenda
• What is Core Animation?
• Layers
• Animating layer properties
• Transactions
• 3D transforms
• Advanced layer effects
• Performance tips & tricks

12 /50
value

What is an animation?

time
13 /50
What can be animated?
• Geometry
• position
• size
• transform (in 3D space)

• Appearance
• borders
• shadow
• background color
• opacity

• And more...
14 /50
Implicit animation
Implicit animation
• Created automatically whenever an animatable property of a
CALayer is changed

• Animates between the current and the new values, using the
default duration and timing function

• Implemented as a transaction committed at the next runloop iteration

• CATransaction allows to override the default animation
properties, e.g.:

• [CATransaction

setAnimationDuration: 5.0]

16 /50
Implicit animation example
layer.position = CGPointMake(...);
[CATransaction setAnimationDuration: 3];
[CATransaction setAnimationTimingFunction: [CAMediaTimingFunction
functionWithName: kCAMediaTimingFunctionEaseInEaseOut]];
layer.position = CGPointMake(...);

17 /50
Disabling implicit animation
• If needed, implicit animation can be disabled:
• [CATransaction

setDisableActions: YES]

• Affects only the current transaction

• To disable implicit animation only on a particular property of
a given layer:

• layer.actions

= @{@"position" : [NSNull null]}

• Affects every following transaction

18 /50
Explicit animation
Explicit animation
• Animation that are explicitly created
• Require more code than implicit animation, but provide more
control over the animation itself

• Allow for more complex effects:
• Keyframe animation
• Animation grouping

20 /50
Explicit animation example
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:
@”position.x”];
animation.fromValue = @(startPosition.x);
animation.toValue = @(endPosition.x);
animation.duration = 3;
animation.timingFunction = [CAMediaTimingFunction functionWithName:
kCAMediaTimingFunctionEaseInEaseOut];
[layer addAnimation: animation forKey: @”animation”];

21 /50
Model vs Presentation
• Explicit animations do not affect the model values of the
layer hierarchy

• Therefore, layer properties do not reflect what is shown on
screen

• Use presentationLayer to get screen values:
• Returns a copy of the layer that represents an approximation of its
current state

• Asking for sublayers returns objects in the presentation tree (not the
model tree)

• Useful for modifying in-flight animations (i.e. for the from
value of the new animation)

22 /50
Making it stick
• Explicitly set the model value to its final value

layer.position = endPosition;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:
@”position.x”];
animation.fromValue = @(startPosition.x);
animation.toValue = @(endPosition.x);
animation.duration = 3;
animation.timingFunction = [CAMediaTimingFunction functionWithName:
kCAMediaTimingFunctionEaseInEaseOut];
[layer addAnimation: animation forKey: @”animation”];

23 /50
Animation delegate
• Explicit animation can have an animation delegate
• Retained by the animation (beware of retain cycles!)

• Gets notified when an animation starts or ends:
• animationDidStart:
• animationDidStop:finished:

24 /50
Explicit animation classes
CAMediaTiming

CAAnimation

duration
beginTime
timeOffset
repeatCount

CAAnimationGroup

CAPropertyAnimation

CABasicAnimation

CATransition

CAKeyframeAnimation
25 /50
Keyframe animation
Keyframe animation

time

27 /50
CAKeyframeAnimation
• Keyframe values can be specified either with:
• values - Array of keyframe values
• path - CGPathRef (only for layer properties that contain a CGPoint data
type)

• Timing can be controlled with:
• keyTimes - Array of floats defining when to apply the corresponding
keyframe value (or path control point)

• timingFunctions - Array of CAMediaTimingFunctions, controlling
the pacing of each keyframe segment (linear, ease in, out, in/out)

• calculationMode - Controls how interpolated values should be
computed (linear, cubic, or discrete)

28 /50
Agenda
• What is Core Animation?
• Layers
• Animating layer properties
• Transactions
• 3D transforms
• Advanced layer effects
• Performance tips & tricks

29 /50
CATransaction
• It is the Core Animation mechanism for batching multiple

layer-tree operations into atomic updates to the render tree

• Every modification to a layer tree must be part of a
transaction

• Implicit:
• Transactions that are created automatically when the layer tree is
modified by a thread without an active transaction

• Committed automatically when the thread's run-loop next iterates

• Explicit:
• Explicitly created (with [CATransaction

begin]) and committed (with

[CATransaction commit])

30 /50
Explicit transactions
• Don’t forget to commit an explicit transaction (or bad things
may happen!)

• Multiple transactions can be nested
• Can have a completion block, called when all subsequently
added animations have completed

[CATransaction begin];
[CATransaction setCompletionBlock: ^{
...
}];
CABasicAnimation *animation = ...
[layer addAnimation: animation forKey: @”animation”];
[CATransaction commit];

31 /50
Agenda
• What is Core Animation?
• Layers
• Animating layer properties
• Transactions
• 3D transforms
• Advanced layer effects
• Performance tips & tricks

32 /50
3D transforms
• Layers can be transformed in 3D space
• The transform property is a 3D transform matrix
(CATransform3D)

• Possible transformations:
• Translate (CATransform3DMakeTranslation)
• Scale (CATransform3DMakeScale)
• Rotation (CATransform3DMakeRotation)

• Perspective can be achieved by manually altering the
transform’s m34 entry:
• transform.m34

= 1.0 / -zDistance;

33 /50
Is it really 3D?
• CALayer uses a flattened hierarchy rendering model
• i.e. it flattens its sublayers into the plane at Z=0

• So, even if we can apply a 3D transform to each of our

layers, we can’t group them into a single 3D object and
apply a 3D transform to that

• It’s a 2.5D model

34 /50
CATransformLayer
• CATransformLayer can be used to create true 3D layer
hierarchies

• i.e. it does not flatten its sublayers

• Because of this, many of the features of the standard
CALayer model are not supported:

• Only the sublayers of a CATransformLayer are rendered
• The opacity property is applied to each sublayer individually
• The hitTest: method should never be called on a transform layer (it
does not have a 2D coordinate space into which the point can be
mapped)

35 /50
Demo
Agenda
• What is Core Animation?
• Layers
• Animating layer properties
• Transactions
• 3D transforms
• Advanced layer effects
• Performance tips & tricks

37 /50
Replicators
• CAReplicatorLayer are special layers that create a
specified number of copies of its sublayer tree

• Each copy is automatically updated every time you add or
change a sublayer of the replicator layer

• Each copy can have geometric, temporal and color
transformations applied to it

38 /50
How to use replicators
CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer layer];
replicatorLayer.instanceCount = 6;
replicatorLayer.instanceTransform = CATransform3DMakeTranslation(50, 0,
0);
replicatorLayer.instanceBlueOffset = -0.2;
[view.layer addSublayer: replicatorLayer];
circleLayer = [CALayer layer];
...
[replicatorLayer addSublayer: circleLayer];

39 /50
Particle emitters
• CAEmitterLayer class implements a particle emitter system

• An emitter has:
• A position (also in the z-axis)
• A shape (point, line, rectangle, circle, sphere, ...)
• A mode (outline, surface, volume, ...)
• An array of emitter cells (each must be an instance of CAEmitterCell)

40 /50
Emitter cells
• An emitter cell represents one source of particles emitted by
a CAEmitterLayer

• It defines the direction and the properties of the emitted
particles:

• birthRate
• velocity
• contents
• color
• emissionLatitude/emissionLongitude
• lifetime

• ...
41 /50
Emitter cells
• For many properties (velocity,

emissionLatitude,
emissionLongitude, color, lifetime, ...) a range

can be defined

• Each emitted particle will have its own value for the property, randomly
chosen within its range

• An emitter cell can also have an array of sub-cells
• Particles emitting particles!

42 /50
Demo
Agenda
• What is Core Animation?
• Layers
• Animating layer properties
• Transactions
• 3D transforms
• Advanced layer effects
• Performance tips & tricks

44 /50
General tips
• Set opaque property to YES for opaque layers
• Avoid CAShapeLayer with complex paths
• Avoid offscreen rendering
• e.g. masks, shadows, ...

• Set shadowPath when using shadows
• Use Instruments’ CoreAnimation template to debug
performance issues

45 /50
Layer caching
•

Layers can be asked to cache theirs contents in a bitmap
• layer.shouldRasterize

= YES

• It will be reused when possible
• May lead to a significant performance improvement

46 /50
Layer caching
• Bitmaps require memory to be stored
• Devices are memory-limited, so cache space is limited

• Improves performance only when the cached bitmap can be
reused

• Caching and not-reusing is more expensive than not caching

• A rasterized layer is not really suited to be scaled
• The cached bitmap has a fixed size, depending on the layer’s size and
the rasterizationScale property

• Rasterization occurs before mask is applied

47 /50
Conclusions
Core Animation allows you to perform:

• Basic animations
• Keyframe-based animations
• More advanced effects:
• 3D transforms
• Replicators
• Particle emitters

48 /50
Q&A
Thank you!
For further information: marco.zoffoli@pragmamark.org

More Related Content

What's hot

Unity mobile game performance profiling – using arm mobile studio
Unity mobile game performance profiling – using arm mobile studioUnity mobile game performance profiling – using arm mobile studio
Unity mobile game performance profiling – using arm mobile studio
Owen Wu
 
[Unite Seoul 2019] Mali GPU Architecture and Mobile Studio
[Unite Seoul 2019] Mali GPU Architecture and Mobile Studio [Unite Seoul 2019] Mali GPU Architecture and Mobile Studio
[Unite Seoul 2019] Mali GPU Architecture and Mobile Studio
Owen Wu
 
[TGDF 2020] Mobile Graphics Best Practices for Artist
[TGDF 2020] Mobile Graphics Best Practices for Artist[TGDF 2020] Mobile Graphics Best Practices for Artist
[TGDF 2020] Mobile Graphics Best Practices for Artist
Owen Wu
 
Android App Development - 12 animations
Android App Development - 12 animationsAndroid App Development - 12 animations
Android App Development - 12 animations
Diego Grancini
 
Basic Android Animation
Basic Android Animation Basic Android Animation
Basic Android Animation
Shilu Shrestha
 
[shaderx7] 8.1 Cross-Platform Rendering Thread : Design and Implementation
[shaderx7] 8.1 Cross-Platform Rendering Thread : Design and Implementation	[shaderx7] 8.1 Cross-Platform Rendering Thread : Design and Implementation
[shaderx7] 8.1 Cross-Platform Rendering Thread : Design and Implementation
종빈 오
 

What's hot (6)

Unity mobile game performance profiling – using arm mobile studio
Unity mobile game performance profiling – using arm mobile studioUnity mobile game performance profiling – using arm mobile studio
Unity mobile game performance profiling – using arm mobile studio
 
[Unite Seoul 2019] Mali GPU Architecture and Mobile Studio
[Unite Seoul 2019] Mali GPU Architecture and Mobile Studio [Unite Seoul 2019] Mali GPU Architecture and Mobile Studio
[Unite Seoul 2019] Mali GPU Architecture and Mobile Studio
 
[TGDF 2020] Mobile Graphics Best Practices for Artist
[TGDF 2020] Mobile Graphics Best Practices for Artist[TGDF 2020] Mobile Graphics Best Practices for Artist
[TGDF 2020] Mobile Graphics Best Practices for Artist
 
Android App Development - 12 animations
Android App Development - 12 animationsAndroid App Development - 12 animations
Android App Development - 12 animations
 
Basic Android Animation
Basic Android Animation Basic Android Animation
Basic Android Animation
 
[shaderx7] 8.1 Cross-Platform Rendering Thread : Design and Implementation
[shaderx7] 8.1 Cross-Platform Rendering Thread : Design and Implementation	[shaderx7] 8.1 Cross-Platform Rendering Thread : Design and Implementation
[shaderx7] 8.1 Cross-Platform Rendering Thread : Design and Implementation
 

Viewers also liked

Nisha parwani, B.Sc. Interior Design ( Project Presentation)
Nisha parwani, B.Sc. Interior Design ( Project Presentation)Nisha parwani, B.Sc. Interior Design ( Project Presentation)
Nisha parwani, B.Sc. Interior Design ( Project Presentation)
dezyneecole
 
2017 Building Bridges VoIP Project Presentation
2017 Building Bridges VoIP Project Presentation2017 Building Bridges VoIP Project Presentation
2017 Building Bridges VoIP Project Presentation
Jane Cox
 
A review of animation techniques for user interface design
A review of animation techniques for user interface designA review of animation techniques for user interface design
A review of animation techniques for user interface design
Jean Vanderdonckt
 
Animation 2013 bis_taj
Animation 2013 bis_tajAnimation 2013 bis_taj
Animation 2013 bis_taj
maaz hamed
 
Tally
TallyTally
portfolio small
portfolio smallportfolio small
portfolio small
Reem Kinani
 
Nikola Dakic - Architectural Portfolio
Nikola Dakic - Architectural PortfolioNikola Dakic - Architectural Portfolio
Nikola Dakic - Architectural Portfolio
nikoladakic
 
Golden Ratio in Architecture
Golden Ratio in ArchitectureGolden Ratio in Architecture
Golden Ratio in Architecture
guest1e1cf87
 
The Golden Mean
The Golden MeanThe Golden Mean
The Golden Mean
Susan Convery Foltz
 
Le modulor final
Le modulor finalLe modulor final
Le modulor final
Aniket Mahajan
 
Architectural Design 1 Lectures by Dr. Yasser Mahgoub - Process
Architectural Design 1 Lectures by Dr. Yasser Mahgoub - ProcessArchitectural Design 1 Lectures by Dr. Yasser Mahgoub - Process
Architectural Design 1 Lectures by Dr. Yasser Mahgoub - Process
Galala University
 
A POWERPOINT PRESENTAION ON READY-MIX CONCRETE
A POWERPOINT PRESENTAION ON READY-MIX CONCRETEA POWERPOINT PRESENTAION ON READY-MIX CONCRETE
A POWERPOINT PRESENTAION ON READY-MIX CONCRETE
kuntansourav
 
Building a ppmo from scratch
Building a ppmo from scratchBuilding a ppmo from scratch
Building a ppmo from scratch
Jane Cox
 
Tally project
Tally projectTally project
Tally project
Piya Nanwani
 
Fundamentals of tally erp 9
Fundamentals of tally erp 9Fundamentals of tally erp 9
Fundamentals of tally erp 9
Accounts Arabia
 
Use of golden ratio in architecture
Use of golden ratio in architectureUse of golden ratio in architecture
Use of golden ratio in architecture
kunalsahu9883
 
Introduction to Animation
Introduction to AnimationIntroduction to Animation
Introduction to Animation
mrnasim
 
Slideshare.Com Powerpoint
Slideshare.Com PowerpointSlideshare.Com Powerpoint
Slideshare.Com Powerpoint
guested929b
 
Slideshare Powerpoint presentation
Slideshare Powerpoint presentationSlideshare Powerpoint presentation
Slideshare Powerpoint presentation
elliehood
 

Viewers also liked (19)

Nisha parwani, B.Sc. Interior Design ( Project Presentation)
Nisha parwani, B.Sc. Interior Design ( Project Presentation)Nisha parwani, B.Sc. Interior Design ( Project Presentation)
Nisha parwani, B.Sc. Interior Design ( Project Presentation)
 
2017 Building Bridges VoIP Project Presentation
2017 Building Bridges VoIP Project Presentation2017 Building Bridges VoIP Project Presentation
2017 Building Bridges VoIP Project Presentation
 
A review of animation techniques for user interface design
A review of animation techniques for user interface designA review of animation techniques for user interface design
A review of animation techniques for user interface design
 
Animation 2013 bis_taj
Animation 2013 bis_tajAnimation 2013 bis_taj
Animation 2013 bis_taj
 
Tally
TallyTally
Tally
 
portfolio small
portfolio smallportfolio small
portfolio small
 
Nikola Dakic - Architectural Portfolio
Nikola Dakic - Architectural PortfolioNikola Dakic - Architectural Portfolio
Nikola Dakic - Architectural Portfolio
 
Golden Ratio in Architecture
Golden Ratio in ArchitectureGolden Ratio in Architecture
Golden Ratio in Architecture
 
The Golden Mean
The Golden MeanThe Golden Mean
The Golden Mean
 
Le modulor final
Le modulor finalLe modulor final
Le modulor final
 
Architectural Design 1 Lectures by Dr. Yasser Mahgoub - Process
Architectural Design 1 Lectures by Dr. Yasser Mahgoub - ProcessArchitectural Design 1 Lectures by Dr. Yasser Mahgoub - Process
Architectural Design 1 Lectures by Dr. Yasser Mahgoub - Process
 
A POWERPOINT PRESENTAION ON READY-MIX CONCRETE
A POWERPOINT PRESENTAION ON READY-MIX CONCRETEA POWERPOINT PRESENTAION ON READY-MIX CONCRETE
A POWERPOINT PRESENTAION ON READY-MIX CONCRETE
 
Building a ppmo from scratch
Building a ppmo from scratchBuilding a ppmo from scratch
Building a ppmo from scratch
 
Tally project
Tally projectTally project
Tally project
 
Fundamentals of tally erp 9
Fundamentals of tally erp 9Fundamentals of tally erp 9
Fundamentals of tally erp 9
 
Use of golden ratio in architecture
Use of golden ratio in architectureUse of golden ratio in architecture
Use of golden ratio in architecture
 
Introduction to Animation
Introduction to AnimationIntroduction to Animation
Introduction to Animation
 
Slideshare.Com Powerpoint
Slideshare.Com PowerpointSlideshare.Com Powerpoint
Slideshare.Com Powerpoint
 
Slideshare Powerpoint presentation
Slideshare Powerpoint presentationSlideshare Powerpoint presentation
Slideshare Powerpoint presentation
 

Similar to Building animated UI with Core Animation

Core animation
Core animationCore animation
Core animation
Weizhong Yang
 
Core animation taobao
Core animation taobaoCore animation taobao
Core animation taobao
yarshure Kong
 
iOS Core Animation
iOS Core AnimationiOS Core Animation
iOS Core Animation
Jussi Pohjolainen
 
CocoaHeads Paris - CATransaction: What the flush?!
CocoaHeads Paris - CATransaction: What the flush?!CocoaHeads Paris - CATransaction: What the flush?!
CocoaHeads Paris - CATransaction: What the flush?!
amadour
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core Animation
John Wilker
 
Peint talk
Peint talkPeint talk
Peint talk
CyruzDraxs
 
CATiled Layer - Melbourne Cocoheads February 2012
CATiled Layer - Melbourne Cocoheads February 2012CATiled Layer - Melbourne Cocoheads February 2012
CATiled Layer - Melbourne Cocoheads February 2012
Jesse Collis
 
Implementing CATiledLayer
Implementing CATiledLayerImplementing CATiledLayer
Implementing CATiledLayer
Jesse Collis
 
CSS3 TTA (Transform Transition Animation)
CSS3 TTA (Transform Transition Animation)CSS3 TTA (Transform Transition Animation)
CSS3 TTA (Transform Transition Animation)
창석 한
 
Сергій Міськів, «SwiftUI: Animations»
Сергій Міськів, «SwiftUI: Animations»Сергій Міськів, «SwiftUI: Animations»
Сергій Міськів, «SwiftUI: Animations»
Sigma Software
 
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon RitterJava Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
JAX London
 
Demystifying Angular Animations
Demystifying Angular AnimationsDemystifying Angular Animations
Demystifying Angular Animations
Gil Fink
 
COMP340 TOPIC 4 THREE.JS.pptx
COMP340 TOPIC 4 THREE.JS.pptxCOMP340 TOPIC 4 THREE.JS.pptx
COMP340 TOPIC 4 THREE.JS.pptx
Egerton University
 
Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)
Marakana Inc.
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshop
Vinay Kumar
 
Hi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreTextHi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreText
Mugunth Kumar
 
Fastest css3 animations
Fastest css3 animations Fastest css3 animations
Fastest css3 animations
Ismail Berkay Beyaz
 
Ask the expert - App performance on Series 40 phones
Ask the expert - App performance on Series 40 phonesAsk the expert - App performance on Series 40 phones
Ask the expert - App performance on Series 40 phones
Microsoft Mobile Developer
 
Flow chart programming
Flow chart programmingFlow chart programming
Flow chart programming
Tearsome Llantada
 
Iagc2
Iagc2Iagc2

Similar to Building animated UI with Core Animation (20)

Core animation
Core animationCore animation
Core animation
 
Core animation taobao
Core animation taobaoCore animation taobao
Core animation taobao
 
iOS Core Animation
iOS Core AnimationiOS Core Animation
iOS Core Animation
 
CocoaHeads Paris - CATransaction: What the flush?!
CocoaHeads Paris - CATransaction: What the flush?!CocoaHeads Paris - CATransaction: What the flush?!
CocoaHeads Paris - CATransaction: What the flush?!
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core Animation
 
Peint talk
Peint talkPeint talk
Peint talk
 
CATiled Layer - Melbourne Cocoheads February 2012
CATiled Layer - Melbourne Cocoheads February 2012CATiled Layer - Melbourne Cocoheads February 2012
CATiled Layer - Melbourne Cocoheads February 2012
 
Implementing CATiledLayer
Implementing CATiledLayerImplementing CATiledLayer
Implementing CATiledLayer
 
CSS3 TTA (Transform Transition Animation)
CSS3 TTA (Transform Transition Animation)CSS3 TTA (Transform Transition Animation)
CSS3 TTA (Transform Transition Animation)
 
Сергій Міськів, «SwiftUI: Animations»
Сергій Міськів, «SwiftUI: Animations»Сергій Міськів, «SwiftUI: Animations»
Сергій Міськів, «SwiftUI: Animations»
 
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon RitterJava Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
 
Demystifying Angular Animations
Demystifying Angular AnimationsDemystifying Angular Animations
Demystifying Angular Animations
 
COMP340 TOPIC 4 THREE.JS.pptx
COMP340 TOPIC 4 THREE.JS.pptxCOMP340 TOPIC 4 THREE.JS.pptx
COMP340 TOPIC 4 THREE.JS.pptx
 
Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshop
 
Hi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreTextHi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreText
 
Fastest css3 animations
Fastest css3 animations Fastest css3 animations
Fastest css3 animations
 
Ask the expert - App performance on Series 40 phones
Ask the expert - App performance on Series 40 phonesAsk the expert - App performance on Series 40 phones
Ask the expert - App performance on Series 40 phones
 
Flow chart programming
Flow chart programmingFlow chart programming
Flow chart programming
 
Iagc2
Iagc2Iagc2
Iagc2
 

Recently uploaded

Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024
Vadym Kazulkin
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Christine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptxChristine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptx
christinelarrosa
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
A Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's ArchitectureA Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's Architecture
ScyllaDB
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
Pablo Gómez Abajo
 

Recently uploaded (20)

Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Christine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptxChristine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptx
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
A Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's ArchitectureA Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's Architecture
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
 

Building animated UI with Core Animation

  • 1. Building animated UI with Core Animation Marco Zoffoli iOS Developer
  • 2. Agenda • What is Core Animation? • Layers • Animating layer properties • Transactions • 3D transforms • Advanced layer effects • Performance tips & tricks 2 /50
  • 3. Agenda • What is Core Animation? • Layers • Animating layer properties • Transactions • 3D transforms • Advanced layer effects • Performance tips & tricks 3 /50
  • 4. What is Core Animation? • Core Animation is an animation framework for animating UI elements and creating visual effects • Available on both iOS and Mac OS X (we’ll cover only iOS) • Just provide a few parameters and Core Animation will do the rest: • Starting point • Ending point • Timing 4 /50
  • 6. Agenda • What is Core Animation? • Layers • Animating layer properties • Transactions • 3D transforms • Advanced layer effects • Performance tips & tricks 6 /50
  • 7. CALayer • A layer represents a rectangular portion of the screen with visual contents • Every UIView has a CALayer, accessible via view.layer • drawRect: actually draws into the backing layer • Model similar to UIView: • addSublayer: • setNeedsDisplay • layoutSublayers • drawInContext: • ... 7 /50
  • 8. CALayer geometry x y layer.position = CGPointMake(150, 200) layer.bounds = CGRectMake(0, 0, 170, 220) layer.transform = CATransform3DMakeRotation(M_PI / 4, 0, 0, 1) + r ye la superlayer 8 /50
  • 9. CALayer geometry layer.anchorPoint = CGPointMake(0.5, 1) layer.transform = CATransform3DMakeRotation(M_PI / 4, 0, 0, 1) ye la + r superlayer y la er 9 /50
  • 10. CALayer appearance layer.cornerRadius = 5.0; layer.borderWidth = 2.0; layer.borderColor = [UIColor redColor].CGColor; layer.shadowOpacity = 0.7; layer.shadowRadius = 5.0; layer.shadowOffset = CGSizeMake(1, 1); layer.shadowColor = [UIColor blackColor].CGColor; layer.mask = maskLayer; superlayer 10 /50
  • 12. Agenda • What is Core Animation? • Layers • Animating layer properties • Transactions • 3D transforms • Advanced layer effects • Performance tips & tricks 12 /50
  • 13. value What is an animation? time 13 /50
  • 14. What can be animated? • Geometry • position • size • transform (in 3D space) • Appearance • borders • shadow • background color • opacity • And more... 14 /50
  • 16. Implicit animation • Created automatically whenever an animatable property of a CALayer is changed • Animates between the current and the new values, using the default duration and timing function • Implemented as a transaction committed at the next runloop iteration • CATransaction allows to override the default animation properties, e.g.: • [CATransaction setAnimationDuration: 5.0] 16 /50
  • 17. Implicit animation example layer.position = CGPointMake(...); [CATransaction setAnimationDuration: 3]; [CATransaction setAnimationTimingFunction: [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut]]; layer.position = CGPointMake(...); 17 /50
  • 18. Disabling implicit animation • If needed, implicit animation can be disabled: • [CATransaction setDisableActions: YES] • Affects only the current transaction • To disable implicit animation only on a particular property of a given layer: • layer.actions = @{@"position" : [NSNull null]} • Affects every following transaction 18 /50
  • 20. Explicit animation • Animation that are explicitly created • Require more code than implicit animation, but provide more control over the animation itself • Allow for more complex effects: • Keyframe animation • Animation grouping 20 /50
  • 21. Explicit animation example CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath: @”position.x”]; animation.fromValue = @(startPosition.x); animation.toValue = @(endPosition.x); animation.duration = 3; animation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut]; [layer addAnimation: animation forKey: @”animation”]; 21 /50
  • 22. Model vs Presentation • Explicit animations do not affect the model values of the layer hierarchy • Therefore, layer properties do not reflect what is shown on screen • Use presentationLayer to get screen values: • Returns a copy of the layer that represents an approximation of its current state • Asking for sublayers returns objects in the presentation tree (not the model tree) • Useful for modifying in-flight animations (i.e. for the from value of the new animation) 22 /50
  • 23. Making it stick • Explicitly set the model value to its final value layer.position = endPosition; CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath: @”position.x”]; animation.fromValue = @(startPosition.x); animation.toValue = @(endPosition.x); animation.duration = 3; animation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut]; [layer addAnimation: animation forKey: @”animation”]; 23 /50
  • 24. Animation delegate • Explicit animation can have an animation delegate • Retained by the animation (beware of retain cycles!) • Gets notified when an animation starts or ends: • animationDidStart: • animationDidStop:finished: 24 /50
  • 28. CAKeyframeAnimation • Keyframe values can be specified either with: • values - Array of keyframe values • path - CGPathRef (only for layer properties that contain a CGPoint data type) • Timing can be controlled with: • keyTimes - Array of floats defining when to apply the corresponding keyframe value (or path control point) • timingFunctions - Array of CAMediaTimingFunctions, controlling the pacing of each keyframe segment (linear, ease in, out, in/out) • calculationMode - Controls how interpolated values should be computed (linear, cubic, or discrete) 28 /50
  • 29. Agenda • What is Core Animation? • Layers • Animating layer properties • Transactions • 3D transforms • Advanced layer effects • Performance tips & tricks 29 /50
  • 30. CATransaction • It is the Core Animation mechanism for batching multiple layer-tree operations into atomic updates to the render tree • Every modification to a layer tree must be part of a transaction • Implicit: • Transactions that are created automatically when the layer tree is modified by a thread without an active transaction • Committed automatically when the thread's run-loop next iterates • Explicit: • Explicitly created (with [CATransaction begin]) and committed (with [CATransaction commit]) 30 /50
  • 31. Explicit transactions • Don’t forget to commit an explicit transaction (or bad things may happen!) • Multiple transactions can be nested • Can have a completion block, called when all subsequently added animations have completed [CATransaction begin]; [CATransaction setCompletionBlock: ^{ ... }]; CABasicAnimation *animation = ... [layer addAnimation: animation forKey: @”animation”]; [CATransaction commit]; 31 /50
  • 32. Agenda • What is Core Animation? • Layers • Animating layer properties • Transactions • 3D transforms • Advanced layer effects • Performance tips & tricks 32 /50
  • 33. 3D transforms • Layers can be transformed in 3D space • The transform property is a 3D transform matrix (CATransform3D) • Possible transformations: • Translate (CATransform3DMakeTranslation) • Scale (CATransform3DMakeScale) • Rotation (CATransform3DMakeRotation) • Perspective can be achieved by manually altering the transform’s m34 entry: • transform.m34 = 1.0 / -zDistance; 33 /50
  • 34. Is it really 3D? • CALayer uses a flattened hierarchy rendering model • i.e. it flattens its sublayers into the plane at Z=0 • So, even if we can apply a 3D transform to each of our layers, we can’t group them into a single 3D object and apply a 3D transform to that • It’s a 2.5D model 34 /50
  • 35. CATransformLayer • CATransformLayer can be used to create true 3D layer hierarchies • i.e. it does not flatten its sublayers • Because of this, many of the features of the standard CALayer model are not supported: • Only the sublayers of a CATransformLayer are rendered • The opacity property is applied to each sublayer individually • The hitTest: method should never be called on a transform layer (it does not have a 2D coordinate space into which the point can be mapped) 35 /50
  • 36. Demo
  • 37. Agenda • What is Core Animation? • Layers • Animating layer properties • Transactions • 3D transforms • Advanced layer effects • Performance tips & tricks 37 /50
  • 38. Replicators • CAReplicatorLayer are special layers that create a specified number of copies of its sublayer tree • Each copy is automatically updated every time you add or change a sublayer of the replicator layer • Each copy can have geometric, temporal and color transformations applied to it 38 /50
  • 39. How to use replicators CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer layer]; replicatorLayer.instanceCount = 6; replicatorLayer.instanceTransform = CATransform3DMakeTranslation(50, 0, 0); replicatorLayer.instanceBlueOffset = -0.2; [view.layer addSublayer: replicatorLayer]; circleLayer = [CALayer layer]; ... [replicatorLayer addSublayer: circleLayer]; 39 /50
  • 40. Particle emitters • CAEmitterLayer class implements a particle emitter system • An emitter has: • A position (also in the z-axis) • A shape (point, line, rectangle, circle, sphere, ...) • A mode (outline, surface, volume, ...) • An array of emitter cells (each must be an instance of CAEmitterCell) 40 /50
  • 41. Emitter cells • An emitter cell represents one source of particles emitted by a CAEmitterLayer • It defines the direction and the properties of the emitted particles: • birthRate • velocity • contents • color • emissionLatitude/emissionLongitude • lifetime • ... 41 /50
  • 42. Emitter cells • For many properties (velocity, emissionLatitude, emissionLongitude, color, lifetime, ...) a range can be defined • Each emitted particle will have its own value for the property, randomly chosen within its range • An emitter cell can also have an array of sub-cells • Particles emitting particles! 42 /50
  • 43. Demo
  • 44. Agenda • What is Core Animation? • Layers • Animating layer properties • Transactions • 3D transforms • Advanced layer effects • Performance tips & tricks 44 /50
  • 45. General tips • Set opaque property to YES for opaque layers • Avoid CAShapeLayer with complex paths • Avoid offscreen rendering • e.g. masks, shadows, ... • Set shadowPath when using shadows • Use Instruments’ CoreAnimation template to debug performance issues 45 /50
  • 46. Layer caching • Layers can be asked to cache theirs contents in a bitmap • layer.shouldRasterize = YES • It will be reused when possible • May lead to a significant performance improvement 46 /50
  • 47. Layer caching • Bitmaps require memory to be stored • Devices are memory-limited, so cache space is limited • Improves performance only when the cached bitmap can be reused • Caching and not-reusing is more expensive than not caching • A rasterized layer is not really suited to be scaled • The cached bitmap has a fixed size, depending on the layer’s size and the rasterizationScale property • Rasterization occurs before mask is applied 47 /50
  • 48. Conclusions Core Animation allows you to perform: • Basic animations • Keyframe-based animations • More advanced effects: • 3D transforms • Replicators • Particle emitters 48 /50
  • 49. Q&A
  • 50. Thank you! For further information: marco.zoffoli@pragmamark.org