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

Mais conteúdo relacionado

Mais procurados

[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
종빈 오
 

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

Destaque

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
 

Destaque (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
 

Semelhante a Building animated UI with Core Animation

Core animation taobao
Core animation taobaoCore animation taobao
Core animation taobao
yarshure Kong
 
CSS3 TTA (Transform Transition Animation)
CSS3 TTA (Transform Transition Animation)CSS3 TTA (Transform Transition Animation)
CSS3 TTA (Transform Transition Animation)
창석 한
 
Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)
Marakana Inc.
 

Semelhante a 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
 
Implementing CATiledLayer
Implementing CATiledLayerImplementing CATiledLayer
Implementing CATiledLayer
 
CATiled Layer - Melbourne Cocoheads February 2012
CATiled Layer - Melbourne Cocoheads February 2012CATiled Layer - Melbourne Cocoheads February 2012
CATiled Layer - Melbourne Cocoheads February 2012
 
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
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 

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