Professional Documents
Culture Documents
Programming Cuide
Contents
Intreductien te Cere Animatien Pregramming Cuide 8
Organization of This Document 8
See Also 9
Wbat Is Cere Animatien1 10
Core Animation Classes 10
Layer Classes 11
Animation and Timing Classes 13
Layout Manager Classes 14
Transaction Management Classes 14
Cere Animatien Rendering Arcbitecture 15
Layer Ceemetry and 7ransferms 17
Layer Coordinate System 17
Specifying a Layer's Ceometry 17
Transforming a Layer's Ceometry 21
Transform Punctions 21
Modifying the Transform Data Structure 23
Modifying a Transform Using Key Paths 24
Layer-7ree Hierarcby 26
what |s a Layer-Tree Hierarchy! 26
Displaying Layers in views 26
Adding and Pemoving Layers from a Hierarchy 27
Pepositioning and Pesizing Layers 28
Autoresizing Layers 28
Clipping Sublayers 30
Previding Layer Centent 31
Providing CALayer Content 31
Setting the Contents Property 31
Using a Delegate to Provide Content 32
Providing CALayer Content by Subclassing 33
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
2
Positioning Content within a Layer 35
Animatien 38
Animation Classes and Timing 38
|mplicit Animation 39
Lxplicit Animation 40
Starting and Stopping Lxplicit Animations 42
Layer Actiens 43
The Pole of Action Ob|ects 43
Defined Search Pattern for Action Keys 43
Adopting the CAAction Protocol 44
Overriding an |mplied Animation 45
Temporarily Disabling Actions 46
7ransactiens 47
|mplicit transactions 47
Lxplicit Transactions 47
Temporarily Disabling Layer Actions 48
Overriding the Duration of |mplied Animations 48
Nesting Transactions 49
Laying Dut Cere Animatien Layers 50
Constraints Layout Manager 50
Cere Animatien xtensiens 7e key-VaIue Ceding 55
Key-value Coding Compliant Container Classes 55
Default value Support 55
wrapping Conventions 56
Key Path Support for Structure Pields 56
Layer StyIe Preperties 59
Ceometry Properties 59
8ackground Properties 60
Layer Content 61
Sublayers Content 62
8order Attributes 63
Pilters Property 64
Shadow Properties 65
Opacity Property 66
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
3
Composite Property 67
Mask Properties 68
xampIe: Cere Animatien kiesk Menu StyIe AppIicatien 69
The User |nterface 69
Lxamining the Nib Pile 70
The Layer Hierarchy 70
Lxamining the Application's Nib 71
Lxamining the Application's Code 72
CCoreAnimationKioskStyleMenu.h and CCoreAnimationKioskStyleMenu.m Piles 72
Lxamining Selectionview.h 72
Lxamining Selectionview.m 73
Performance Considerations 81
AnimatabIe Preperties 82
CALayer Animatable Properties 82
C|Pilter Animatable Properties 84
Decument Revisien Histery 85
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
4
Pigures, Tables, and Listings
Wbat Is Cere Animatien1 10
Pigure 1 Core Animation class hierarchy 11
Cere Animatien Rendering Arcbitecture 15
Pigure 1 Core Animation Pendering Architecture 15
Layer Ceemetry and 7ransferms 17
Pigure 1 CALayer geometry properties 18
Pigure 2 Three anchorPoint values 19
Pigure 3 Anchor Point of (0.5,0.5) 20
Pigure 4 Layer Origin of (0.0,0.0) 20
Table 1 CATransform3D transform functions for translation, rotation, and scaling 22
Table 2 CATransform3D transform functions for CCAffineTransform conversion 22
Table 3 CATransform3D transform functions for testing equality 23
Table 4 CATransform3D key paths 24
Listing 1 CATransform3D structure 23
Listing 2 Modifying the CATransform3D data structure directly 24
Layer-7ree Hierarcby 26
Pigure 1 Layer autoresizing mask constants 29
Pigure 2 Lxample values of the masksTo8ounds property 30
Table 1 Layer-tree management methods. 27
Table 2 Autoresizing mask values and descriptions 28
Listing 1 |nserting a layer into a view 27
Previding Layer Centent 31
Pigure 1 Position constants for a layer's contentsCravity property 36
Pigure 2 Scaling constants for a layer's contentsCravity property 37
Table 1 Positioning constants for a layer's contentsCravity property 35
Table 2 Scaling Constants Por A Layer's coh1eh1sCJav11y Property 36
Listing 1 Setting a layer's contents property 31
Listing 2 Lxample implementation of the delegate method displayLayer: 32
Listing 3 Lxample implementation of the delegate method drawLayer:inContext: 33
Listing 4 Lxample override of the CALayer display method 34
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
5
Listing 5 Lxample override of the CALayer draw|nContext: method 34
Animatien 38
Listing 1 |mplicitly animating a layer's position property 39
Listing 2 |mplicitly animating multiple properties of multiple layers 39
Listing 3 Lxplicit animation 40
Listing 4 Continuous explicit animation example 40
Layer Actiens 43
Table 1 Action triggers and their corresponding identifiers 43
Listing 1 runActionPorKey:ob|ect:arguments: implementation that initiates an animation 44
Listing 2 |mplied animation for the contents property 45
Listing 3 |mplied animation for the sublayers property 46
7ransactiens 47
Listing 1 Animation using an implicit transaction 47
Listing 2 Temporarily disabling a layer's actions 48
Listing 3 Overriding the animation duration 48
Listing 4 Nesting explicit transactions 49
Laying Dut Cere Animatien Layers 50
Pigure 1 Constraint layout manager attributes 51
Pigure 2 Lxample constraints based layout 52
Listing 1 Configuring a layer's constraints 52
Cere Animatien xtensiens 7e key-VaIue Ceding 55
Listing 1 Lxample implementation of defaultvaluePorKey: 56
Layer StyIe Preperties 59
Pigure 1 Layer geometry 59
Pigure 2 Layer with background color 60
Pigure 3 Layer displaying a content image 61
Pigure 4 Layer displaying the sublayers content 62
Pigure 5 Layer displaying the border attributes content 63
Pigure 6 Layer displaying the filters properties 64
Pigure 7 Layer displaying the shadow properties 65
Pigure 8 Layer including the opacity property 66
Pigure 9 Layer composited using the compositingPilter property 67
Pigure 10 Layer composited with the mask property 68
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
6
xampIe: Cere Animatien kiesk Menu StyIe AppIicatien 69
Pigure 1 Core Animation Kiosk Menu |nterface 70
Pigure 2 Layer Hierarchy Por CCoreAnimationKioskStyleMenu Application 70
Pigure 3 MainMenu.nib Pile 71
Pigure 4 Alternate |nterface with 8lack 8ackground. 81
Listing 1 Selectionview.h Pile Listing 72
Listing 2 |mplementation of awakePromNib 74
Listing 3 Configuration of the 8ackground rootLayer 75
Listing 4 Setup menuLayers Array. The Selectable Menu |tems. 76
Listing 5 Setup selectionLayer. Used to Display the Currently Selected |tem. 78
Listing 6 Handle Changes in Selection 79
Listing 7 Handling Up and Down Key Presses 80
Listing 8 Dealloc and Cleanup 80
AnimatabIe Preperties 82
Table 1 Default |mplied 8asic Animation 84
Table 2 Default |mplied Transition 84
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
7
This document describes the fundamental concepts involved in using Core Animation. Core Animation is an
Ob|ective-C framework that combines a high-performance compositing engine with a simple to use animation
programming interface.
ou should read this document to gain an understanding of working with Core Animation in a Cocoa application.
!le Ooject|ve-C ltotomm|n lonuoe should be considered a prerequisite because Core Animation makes
extensive use of Ob|ective-C properties. ou should also be familiar with key-value coding as described in
ley-volue CoJ|nltotomm|nCu|Je . Pamiliarity withthe uartz 2Dimagingtechnologies describedinuottz
20 ltotomm|n Cu|Je is also helpful, although not required.
ou can build Cocoa applications for two platforms: the OS X operating system and iOS, the operating system
for multi-touch devices such as iPhone and iPod touch. Core Animation Programming Cuide presents
Cocoa-related information for both platforms, integrating the information as much as possible and pointing
out platform differences when necessary.
Organization of This Document
Cote An|mot|on ltotomm|n Cu|Je consists of the following articles:
"what |s Core Animation! (page 10) provides an overview of Core Animation's capabilities.
"Layer Ceometry and Transforms (page 17) describes layer geometry and transformations.
"Layer-Tree Hierarchy (page 26) describes the layer-tree and how an application can manipulate it.
"Providing Layer Content (page 31) describes how to provide basic layer content.
"Layer Actions (page 43) describes layer actions and how to implement implicit animations.
"Laying Out Core Animation Layers (page 50) describes the constraints layout manager
"Core Animation Lxtensions To Key-value Coding (page 55) describes the key-value coding extensions
that Core Animation provides.
"Layer Style Properties (page 59) describes the layer style properties and provides examples of their visual
effects.
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
8
|ntroduction to Core Animation Programming
Cuide
"Lxample: Core Animation Kiosk Menu Style Application (page 69) dissects a Core Animation driven user
interface.
"Animatable Properties (page 82) summarizes the animatable properties of layers and filters.
See Also
These programming guides discuss some of the technologies that are used by Core Animation:
An|mot|on !yes onJ !|m|n ltotomm|n Cu|Je describes the animation classes and timing features used
by Core Animation.
Cote An|mot|on Cooloool contains code fragments that demonstrate common Core Animation tasks.
uottz 20 ltotomm|n Cu|Je describes the two-dimensional drawing engine used to draw the content
of a CALayeJ instance.
Cote lmoe ltotomm|n Cu|Je describes the OS X image processing technology and shows how to use
the Core |mage AP|.
Intreductien te Cere Animatien Pregramming Cuide
See Also
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
9
Core Animation is a collection of Ob|ective-C classes for graphics rendering, pro|ection, and animation. |t
provides fluid animations using advanced compositing effects while retaining a hierarchical layer abstraction
that is familiar to developers using the Application Kit and Cocoa Touch view architectures.
Dynamic, animated user interfaces are hard to create, but Core Animation makes creating these interfaces
easier by providing:
A familiar view-like abstraction that allows you to create complex user interfaces using a hierarchy of layer
ob|ects.
A lightweight data structure. ou can display and animate hundreds of layers simultaneously.
An abstract animation interface that allows animations to run on a separate thread, independent of your
application's run loop. Once an animation is configured and starts, Core Animation assumes full responsibility
for running it at frame rate.
|mproved application performance. Applications need only redraw content when it changes. Minimal
application interaction is required for resizing and providing layout services layers. Core Animation also
eliminates application code that runs at the animation frame-rate.
A flexible layout manager model, including a manager that allows the position and size of a layer to be
set relative to attributes of sibling layers.
Using Core Animation, developers can create dynamic user interfaces for their applications without having to
use low-level graphics AP|s such as OpenCL to get respectable animation performance.
Core Animation Classes
Core Animation classes can be grouped into several categories:
A transaction class that groups multiple layer changes into an atomic update
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
10
what |s Core Animation!
The basic Core Animation classes are contained in the uartz Core framework, although additional layer classes
can be defined in other frameworks. "Core Animation Classes shows the class hierarchy of Core Animation.
Iigure 1 Core Animation class hierarchy
QuartzCore.framework
NSObject
CABasicAnimation
CAKeyframeAnimation
CAAnimationGroup
CAPropertyAnimation
CATransition
CAScrollLayer
CAEAGLLayer *
CATiledLayer
CAConstraintLayoutManager
CAConstraint
CAMediaTimingFunction
CARenderer
CATransaction
QuartzComposer.framework
CATextLayer
QTKit.framework
CAOpenGLLayer
QTCaptureLayer
QTMovieLayer
CAAnimation
<CAAction, CAMediaTiming>
CALayer
<CAMediaTiming>
QCCompositionLayer
* iPhone OS only
Layer Classes
The layer classes are the foundation of Core Animation and provide an abstraction that should be familiar to
developers who have used NSv1ew or bTv1ew. 8asic layer functionality is provided by the CALayeJ class,
which is the parent class for all types of Core Animation layers.
As with an instance of a viewclass, a CALayeJ instance has a single parent layer (the superlayer) and a collection
of sublayers, creating a hierarchy of layers that is referred to as the layer tree. Layers are drawn from back to
front |ust like views and specify their geometry relative to their superlayer, creating a local coordinate system.
However, layers allow a more complex visual display by incorporating transform matrices that allow you to
rotate, skew, scale, and pro|ect the layer content. "Layer Ceometry and Transforms (page 17) discusses layer
geometry and transforms in more detail.
CALayeJ diverges from the Application Kit and Cocoa Touch view classes in that it is not necessary to subclass
CALayeJ in order to display content. The content displayed by a CALayeJ instance can be provided by:
Wbat Is Cere Animatien1
Core Animation Classes
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
11
Setting the layer's content property to a Core Craphics image representation directly, or through delegation.
Providing a delegate that draws directly into a Core Craphics image context.
Setting any of the number of visual style properties that all layer types have in common, for example,
background colors, opacity, and masking. Mac apps also have access to visual properties that make use
of Core |mage filters.
Subclassing CALayeJ and implementing any of the above techniques in a more encapsulated manner.
"Providing Layer Content (page 31) describes the available techniques for providing the content for a layer.
The visual style properties and the order in which they are applied to the content of a layer is discussed in
"Layer Style Properties (page 59).
|n addition to the CALayeJ class, the Core Animation class collection provides additional classes that allow
applications to display other types of content. The available classes differ slightly between OS X and iOS. The
following classes are available on both OS X and iOS:
CAScJo11LayeJ class is a subclass of CALayeJ that simplifies displaying a portion of a layer. The extent
of the scrollable area of a CAScJo11LayeJ ob|ect is defined by the layout of its sublayers. CAScJo11LayeJ
does not provide keyboard or mouse event-handling, nor does it provide visible scrollers.
CATex1LayeJ is a convenience class that creates a layer's content from a string or attributed string.
CAT11edLayeJ allows the display of large and complex images in incremental stages.
OS X provides these additional classes:
CA0pehCLLayeJ provides an OpenCL rendering environment. ou must subclass this class to provide
content using OpenCL. The content can be static or can be updated over time.
0T^ov1eLayeJ and 0TCap1uJeLayeJ (provided by the TKit framework) provides playback of uickTime
movies and live video.
iOS adds the following class:
CATJahs111oh provides a transition effect that affects the entire layer's content. |t fades, pushes, or
reveals layer content when animating. The stock transition effects can be extended by providing your own
custom Core |mage filters.
CAAh1ma11ohCJoup allows an array of animation ob|ects to be grouped together and run concurrently.
Wbat Is Cere Animatien1
Core Animation Classes
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
13
CAPJopeJ1yAh1ma11oh is an abstract subclass that provides support for animating a layer property
specified by a key path.
CAKey1JameAh1ma11oh provides support for key frame animation. ou specify the key path of the layer
property to be animated, an array of values that represent the value at each stage of the animation, as
well as arrays of key frame times and timing functions. As the animation runs, each value is set in turn
using the specified interpolation.
These animation classes are used by both Core Animation and Cocoa Animation proxies. "Animation (page
38) describes the classes as they pertain to Core Animation, An|mot|on !yes onJ !|m|n ltotomm|n Cu|Je
contains a more in-depth exploration of their capabilities.
Layout Manager Classes
Application Kit view classes provide the classic "struts and springs" model of positioning layers relative to their
superlayer. while layers support this model, Core Animation on OS X also provides a more flexible layout
manager mechanism that allows developers to write their own layout managers.
Core Animation's CACohs1Ja1h1 class is a layout manager that arranges sublayers using a set of constraints
that you specify. Lach constraint (encapsulated by instances of the CACohs1Ja1h1 class) describes the
relationship of one geometric attribute of a layer (the left, right, top, or bottomedge or the horizontal or vertical
center) in relation to a geometric attribute of one of its sibling layers or its superlayer.
Layout managers in general, and the constraint layout manager are discussed in "Laying Out Core Animation
Layers (page 50)
Transaction Management Classes
Lvery modification to an animatable property of a layer must be part of a transaction. CATJahsac11oh is the
Core Animation class responsible for batching multiple animation operations into atomic updates to the display.
Nested transactions are supported.
Core Animation supports two types of transactions: implicit transactions and explicit transactions. |mplicit
transactions are created automatically when an animatable property of a layer is modified by a thread without
an active transaction and are committed automatically when the thread's run-loop next iterates. Lxplicit
transactions occur when the application sends the CATJahsac11oh class a begin message before modifying
the layer, and a commit message afterwards.
Transaction management is discussed in "Transactions (page 47).
Wbat Is Cere Animatien1
Core Animation Classes
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
14
while there are obvious similarities between Core Animation layers and Cocoa views the biggest conceptual
divergence is that layers do not render directly to the screen.
where NSv1ew and bTv1ew are clearly viewob|ects in the model-view-controller design pattern, Core Animation
layers are actually model ob|ects. They encapsulate geometry, timing and visual properties, and they provide
the content that is displayed, but the actual display is not the layer's responsibility.
Lach visible layer tree is backed by two corresponding trees: a presentation tree and a render tree. Pigure 1
shows an example layer-tree using the Core Animation layer classes available in OS X.
Iigure 1 Core Animation Pendering Architecture
CALayer CALayer
Layer-Tree Presentation Tree
Object Model Values Presentation Values
Render-Tree (Private)
CATextLayer
CATextLayer
CAOpenGLLayer
CATiledLayer
CALayer
CALayer
CATextLayer
CATextLayer
CAOpenGLLayer
CATiledLayer
CALayer
CALayer
The layer tree contains the ob|ect model values for each layer. These are the values you set when you assign
a value to a layer property.
The presentation tree contains the values that are currently being presented to the user as an animation takes
place. Por example, setting a new value for the backgJouhdCo1oJ of a layer immediately changes the value
in the layer tree. However, the backgJouhdCo1oJ value in the corresponding layer in the presentation tree
will be updated with the interpolated colors as they are displayed to the user.
The render-tree uses the value in the presentation-tree when rendering the layer. The render-tree is responsible
for performing the compositing operations independent of application activity, rendering is done in a separate
process or thread so that it has minimal impact on the application's run loop.
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
15
Core Animation Pendering Architecture
ou can query an instance of CALayeJ for its corresponding presentation layer while an animation transaction
is in process. This is most useful if you intend to change the current animation and want to begin the new
animation from the currently displayed state.
Cere Animatien Rendering Arcbitecture
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
16
This chapter describes the components of a layer's geometry, howthey interrelate, and howtransformmatrices
can produce complex visual effects.
Layer Coordinate System
The coordinate system for layers differs depending on the current platform. |n iOS, the default coordinate
system origin is in the top-left corner of the layer and positive values extend down and to the right of that
origin point. |n OS X, the default coordinate system origin is in the lower-left corner of the layer and positive
values extend up and to the right of that point. All coordinate values are specified as floating-point numbers.
And any layers you create on a given platformuse the default coordinate systemassociated with that platform.
Lvery layer ob|ect defines and maintains its own coordinate system, and all content in a layer is positioned
relative to this coordinate system. This is true both for the layer contents itself and for any sublayers. 8ecause
each layer defines its own coordinate system, the CALayeJ class provides methods to convert point, rectangle
and size values from the coordinate system of one layer to another.
Some layer-related properties measure their values using the unit coordinate space. The unit coordinate space
is a way of specifying values relative to the bounds of the layer but without tying that property to the exact
bounds values. A given x or y coordinate in the unit coordinate space is always in the range of 0.0 to 1.0.
Specifying a value of 0.0 along the x axis yields a point on the left edge of the layer while specifying a value
of 1.0 yields a point on the right edge of the layer. (Por y values, which value is along the top edge and which
value is along the bottom edge depends on the underlying platform and follows the same rules as previously
described.) A point of (0.5, 0.5) yields a point in the exact center of the layer.
Specifying a Layer's Ceometry
while layers and the layer-tree are analogous to views and view hierarchies in many ways, a layer's geometry
is specified in a different, and often simpler, manner. All of a layer's geometric properties, including the layer's
transform matrices, can be implicitly and explicitly animated.
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
17
Layer Ceometry and Transforms
Pigure 1 shows the properties used to specify a layer's geometry in context.
Iigure 1 CALayer geometry properties
bounds.width
outerLayer
innerLayer
bounds.height
position
frame
bounds.origin
cornerRadius
The pos111oh property is a CCPo1h1 that specifies the position of the layer relative to its superlayer, and is
expressed in the superlayer's coordinate system.
The bouhds property is a CCRec1 that provides the size of the layer (bouhds.s1ze) and the origin
(bouhds.oJ1g1h). The bounds origin is used as the origin of the graphics context when you override a layer's
drawing methods.
Layers have an implicit 1Jame that is a function of the pos111oh, bouhds, ahchoJPo1h1, and 1Jahs1oJm
properties. Setting a newframe rectangle changes the layer's pos111oh and bouhds properties appropriately,
but the frame itself is not stored. when a new frame rectangle is specified the bounds origin is undisturbed,
while the bounds size is set to the size of the frame. The layer's position is set to the proper location relative
to the anchor point. when you get the 1Jame property value, it is calculated relative to the pos111oh, bouhds,
and ahchoJPo1h1 properties.
The ahchoJPo1h1 property is a CCPo1h1 that specifies a location within the bounds of a layer that corresponds
with the position coordinate. The anchor point specifies howthe bounds are positioned relative to the pos111oh
property, as well as serving as the point that transforms are applied around. |t is expressed in the unit coordinate
system-the (0.0,0.0) value is located closest to the layer's origin and (1.0,1.0) is located in the opposite corner.
Applying a transform to the layer's parent (if one exists) can alter the ahchoJPo1h1 orientation, depending
on the parent's coordinate system on the y-axis.
when you specify the frame of a layer, pos111oh is set relative to the anchor point. when you specify the
pos111oh of the layer, bouhds is set relative to the anchor point.
Layer Ceemetry and 7ransferms
Specifying a Layer's Ceometry
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
18
iDS Nete: The following examples show a layer in OS X, where the default coordinate system origin
is located in the lower-left corner. On iOS, the layer's origin would be in the upper-left corner and
positive values would extend down and to the right. This changes the specific values shown, but
not the concepts.
Pigure 2 shows three example values for an anchor point.
Iigure 2 Three anchorPoint values
% $
&
The default value for ahchoJPo1h1 is (0.5,0.5) which corresponds to the center of the layer's bounds (shown
as point A in Pigure 2). Point 8 shows the position of an anchor point set to (0.0,0.5). Pinally, point C (1.0,0.0)
specifies that the layer's pos111oh is set to the bottom right corner of the frame. This diagram is specific to
layers in OS X. |n iOS, layers use a different default coordinate system, where (0.0,0.0) is in the top-left corner
and (1.0,1.0) is in the lower-right.
Layer Ceemetry and 7ransferms
Specifying a Layer's Ceometry
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
19
The relationship of the 1Jame, bouhds, pos111oh, and ahchoJPo1h1 properties is shown in Pigure 3.
Iigure 3 Anchor Point of (0.5,0.5)
bounds = (0.0,0.0, 120.0,80.0)
frame = (40.0,60.0, 120.0,80.0)
anchorPoint = (0.5,0.5)
position = (100.0, 100.0)
GSBNF
BODIPS1PJOU
rotation applied
PSJHJOBM
GSBNF
SPUBUFE
GSBNF
scale applied
PSJHJOBM
GSBNF
TDBMFE
GSBNF
|n this example the ahchoJPo1h1 is set to the default value of (0.5,0.5), which corresponds to the center of
the layer. The pos111oh of the layer is set to (100.0,100.0), and the bouhds is set to the rectangle (0.0, 0.0,
120.0, 80.0). This causes the frame property to be calculated as (40.0, 60.0, 120.0, 80.0).
|f you created a new layer, and set only the layer's frame property to (40.0, 60.0, 120.0, 80.0), the pos111oh
property would be automatically set to (100.0,100.0), and the bounds property to (0.0, 0.0, 120.0, 80.0).
Pigure 4 shows a layer with the same 1Jame rectangle as the layer in Pigure 3. However, in this case the
ahchoJPo1h1 of the layer is set to (0.0,0.0), which corresponds with the bottom left corner of the layer.
Iigure 4 Layer Origin of (0.0,0.0)
anchorPoint = (0.0,0.0)
position = (40.0, 60.0)
bounds = (0.0,0.0, 120.0,80.0)
frame = (40.0,60.0, 120.0,80.0)
GSBNF
BODIPS1PJOU
rotation applied
PSJHJOBM
GSBNF
SPUBUFE
GSBNF
scale applied
PSJHJOBM
GSBNF
TDBMFE
GSBNF
with the frame set to (40.0, 60.0, 120.0, 80.0), the value of the bouhds property is the same, but the value of
the pos111oh property has changed.
Layer Ceemetry and 7ransferms
Specifying a Layer's Ceometry
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
20
Another aspect of layer geometry that differs from Cocoa views is that you can specify a radius that is used to
round the corners of the layer. The coJheJRad1us property specifies a radius the layer uses when drawing
content, clipping sublayers, and drawing the border and shadow.
The zPos111oh property specifies the z-axis component of the layer's position. The zPos111oh is intended
to be used to set the visual position of the layer relative to its sibling layers. |t should not be used to specify
the order of layer siblings, instead reorder the layer in the sublayer array.
Transforming a Layer's Ceometry
Once established, you can transform a layer's geometry using matrix transformations. The CATJahs1oJm30
data structure defines a homogenous three-dimensional transform (a 4 by 4 matrix of CCF1oa1 values) that
is used to rotate, scale, offset, skew, and apply perspective transformations to a layer.
Two layer properties specify transform matrices: 1Jahs1oJm and sub1ayeJTJahs1oJm. The matrix specified
by the 1Jahs1oJm property is applied to the layer and its sublayers relative to the layer's ahchoJPo1h1. Pigure
3 shows how rotation and scaling transforms affect a layer when using an anchorPoint of (0.5,0.5), the default
value. Pigure 4 shows how the same transform matrices affect a layer when using an anchorPoint of (0.0,0.0).
The matrix specified by the sub1ayeJTJahs1oJm property is applied only to the layer's sublayers, rather than
to the layer itself.
ou create and modify CATJahs1oJm30 data structures in one of the following ways:
Complex interfaces can be assembled using simpler layers, avoiding monolithic and complex subclassing.
Layers are well suited to this type of 'stacking' due to their complex compositing capabilities.
Lach layer declares its own coordinate system relative to its superlayer's coordinate system. when a layer
is transformed, its sublayers are transformed within it.
A layer-tree is dynamic. |t can be reconfigured as an application runs. Layers can be created, added as a
sublayer first of one layer, then of another, and removed from the layer-tree.
Displaying Layers in views
Core Animation doesn't provide a means for actually displaying layers in a window, they must be hosted by a
view. when paired with a view, the view must provide event-handling for the underlying layers, while the
layers provide display of the content.
The viewsystemin iOS is built directly on top of Core Animation layers. Lvery instance of bTv1ew automatically
creates an instance of a CALayeJ class and sets it as the value of the view's 1ayeJ property. ou can add
sublayers to the view's layer as needed.
On OS X you must configure an NSv1ew instance in such a way that it can host a layer. To display the root layer
of a layer tree, you set a view's layer and then configure the view to use layers as shown in Table 2.
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
26
Layer-Tree Hierarchy
Listing 1 |nserting a layer into a view
// 1hev1ew 1s ah ex1s11hg v1ew 1h a w1hdow
// 1heRoo1LayeJ 1s 1he Joo1 1ayeJ o1 a 1ayeJ 1Jee
[1hev1ew se1LayeJ: 1heRoo1LayeJ],
[1hev1ew se1Wah1sLayeJ:YES],
Adding and Pemoving Layers from a Hierarchy
Simply instantiating a layer instance doesn't insert it into a layer-tree. |nstead you add, insert, replace, and
remove layers from the layer-tree using the methods described in .Table 1.
7abIe 1 Layer-tree management methods.
ResuIt Metbed
Appends the layer to the receiver's sublayers array. addSub1ayeJ:
|nserts the layer as a sublayer of the receiver at the specified index. 1hseJ1Sub1ayeJ: a1Thdex:
|nserts the layer into the receiver's sublayers array, below the
specified sublayer.
1hseJ1Sub1ayeJ: be1ow:
|nserts the layer into the receiver's sublayers array, above the
specified sublayer.
1hseJ1Sub1ayeJ: above:
Pemoves the receiver from the sublayers array or mask property
of the receiver's superlayer.
JemoveFJomSupeJ1ayeJ
Peplaces the layer in the receiver's sublayers array with the specified
new layer.
Jep1aceSub1ayeJ: w11h:
ou can also set the sublayers of a layer using an array of layers, and setting the intended superlayer's sublayers
property. when setting the sublayers property to an array populated with layer ob|ects you must ensure that
the layers have had their superlayer set to h11.
8y default, inserting and removing layers from a visible layer-tree triggers an animation. when a layer is added
as a sublayer the animation returned by the parent layer for the action identifier kCA0h0JdeJTh is triggered.
when a layer is removed from a layer's sublayers the animation returned by the parent layer for the action
Layer-7ree Hierarcby
Adding and Pemoving Layers from a Hierarchy
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
27
identifier kCA0h0JdeJ0u1 is triggered. Peplacing a layer in a sublayer causes the animation returned by the
parent layer for the action identifier kCATJahs111oh to be triggered. ou can disable animation while
manipulating the layer-tree, or alter the animation used for any of the action identifiers.
Pepositioning and Pesizing Layers
After a layer has been created, you can move and resize it programmatically simply by changing the value of
the layer's geometry properties: 1Jame, bouhds, pos111oh, ahchoJPo1h1, or zPos111oh.
|f a layer's heeds01sp1ay0hBouhdsChahge property is LS, the layer's content is recached when the layer's
bounds changes. 8y default the heeds01sp1ay0hBouhdsChahge property is no.
8y default, setting the 1Jame, bouhds, pos111oh, ahchoJPo1h1, and zPos111oh properties causes the layer
to animate the new values.
Autoresizing Layers
CALayeJ provides a mechanismfor automatically moving and resizing sublayers in response to their superlayer
being moved or resized. |n many cases simply configuring the autoresizing mask for a layer provides the
appropriate behavior for an application.
A layer's autoresizing mask is specified by combining the CAAu1oJes1z1hg^ask constants using the bitwise
0R operator and the layer's au1oJes1z1hg^ask property to the resulting value. Table 2 shows each mask
constant and how it effects the layer's resizing behavior.
7abIe 2 Autoresizing mask values and descriptions
Descriptien Auteresizing Mask
|f set, the layer's height changes proportionally to the change in the
superlayer's height. Otherwise, the layer's height does not change relative
to the superlayer's height.
kCALayeJhe1gh1-
S1zab1e
|f set, the layer's width changes proportionally to the change in the
superlayer's width. Otherwise, the layer's width does not change relative
to the superlayer's width.
kCALayeJW1d1hS1zab1e
|f set, the layer's left edge is repositioned proportionally to the change
in the superlayer's width. Otherwise, the layer's left edge remains in the
same position relative to the superlayer's left edge.
kCALayeJ^1hX^aJg1h
Layer-7ree Hierarcby
Pepositioning and Pesizing Layers
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
28
Descriptien Auteresizing Mask
|f set, the layer's right edge is repositioned proportionally to the change
in the superlayer's width. Otherwise, the layer's right edge remains in
the same position relative to the superlayer.
kCALayeJ^axX^aJg1h
|f set, the layer's top edge is repositioned proportionally to the change
in the superlayer's height. Otherwise, the layer's top edge remains in the
same position relative to the superlayer.
kCALayeJ^axY^aJg1h
|f set, the layer's bottomedge is repositioned proportional to the change
in the superlayer's height. Otherwise, the layer's bottom edge remains
in the same position relative to the superlayer.
kCALayeJ^1hY^aJg1h
Por example, to keep a layer in the lower-left corner of its superlayer, you use the mask kCALayeJ^axX^aJg1h
] kCALayeJ^axY^aJg1h. when more than one aspect along an axis is made flexible, the resize amount is
distributed evenly among them. Pigure 1 provides a graphical representation of the position of the constant
values.
Iigure 1 Layer autoresizing mask constants
kCALayerWidthSizable
kCALayerMaxXMargin
kCALayerMaxYMargin
kCALayerHeightSizable
SuperIayer
Layer
kCALayerMinYMargin
kCALayerMinXMargin
(0.0, 0.0)
when one of these constants is omitted, the layer's layout is fixed in that aspect, when a constant is included
in the mask the layer's layout is flexible in that aspect.
A subclass can override the CALayeJ methods Jes1zeSub1ayeJsW11h01dS1ze: and
Jes1zeW11h01dSupeJ1ayeJS1ze: to customize the autoresizing behavior for a layer. A layers
Jes1zeSub1ayeJsW11h01dS1ze: method is invoked automatically by a layer whenever bounds property
changes, and sends a Jes1zeW11h01dSupeJ1ayeJS1ze: message to each sublayer. Lach sublayer compares
the old bounds size to the new size and ad|usts its position and size according to its autoresize mask.
Layer-7ree Hierarcby
Pepositioning and Pesizing Layers
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
29
Clipping Sublayers
when subviews of a Cocoa view lie outside of the parent view's bounds, the views are clipped to the parent
view. Layers remove this limitation, allowing sublayers to be displayed in their entirety, regardless of their
position relative to the parent layer.
The value of a layer's masksToBouhds property determines if sublayers are clipped to the parent. The default
value of the masksToBouhds property is N0, which prevents sublayers frombeing clipped to the parent. Pigure
2 shows the results of setting the masksTo8ounds for 1ayeJA and how it will affect the display of 1ayeJB and
1ayeJC.
Iigure 2 Lxample values of the masksTo8ounds property
MBZFS#
MBZFS$
MBZFS"
/D\HU7UHH
MBZFS"
MBZFS# MBZFS$
MBZFS"NBTLT5P#PVOET/0
MBZFS$
MBZFS"NBTLT5P#PVOET:&4
MBZFS"
MBZFS#
Layer-7ree Hierarcby
Clipping Sublayers
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
30
when using Cocoa views you must subclass NSv1ew or bTv1ew and implement dJawRec1: in order to display
anything. However CALayeJ instances can often be used directly, without requiring subclassing. 8ecause
CALayeJ is a key-value coding compliant container class, that is you can store arbitrary values in any instance,
subclassing can often be avoided entirely.
Providing CALayer Content
ou specify the content of a CALayeJ instance in one of the following ways:
Lxplicitly set the coh1eh1s property of a layer instance using a CCTmageRe1 that contains the content
image.
CAKey1JameAh1ma11oh provides support for key frame animation. ou specify the key path of the layer
property to be animated, an array of values that represent the value at each stage of the animation, as
well as arrays of key frame times and timing functions. As the animation runs, each value is set in turn
using the specified interpolation.
CATJahs111oh provides a transition effect that affects the entire layer's content. |t fades, pushes, or
reveals layer content when animating. The stock transition effects can be extended by providing your own
custom Core |mage filters.
CAAh1ma11ohCJoup allows an array of animation ob|ects to be grouped together and run concurrently.
|n addition to specifying the type of animation to perform, you must also specify the duration of the animation,
the pacing (how the interpolated values are distributed across the duration), if the animation is to repeat and
how many times, whether it should automatically reverse when each cycle is completed, and its visual state
when the animation is completed. The animation classes and the CA^ed1aT1m1hg protocol provides all this
functionality and more.
CAAh1ma11oh and its subclasses and the timing protocols are shared by both Core Animation and the Cocoa
Animation Proxy functionality. The classes are described in detail in An|mot|on !yes onJ !|m|n ltotomm|n
Cu|Je .
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
38
Animation
|mplicit Animation
Core Animation's implicit animation model assumes that all changes to animatable layer properties should be
gradual and asynchronous. Dynamically animated scenes can be achieved without ever explicitly animating
layers. Changing the value of an animatable layer property causes the layer to implicitly animate the change
from the old value to the new value. while an animation is in-flight, setting a new target value causes the
animation transition to the new target value from its current state.
Listing 1 shows how simple it is to trigger an implicit animation that animates a layer from its current position
to a new position.
Listing 1 |mplicitly animating a layer's position property
// assume 1ha1 1he 1ayeJ 1s cuJJeh1 pos111ohed a1 {100.0,100.0)
1heLayeJ.pos111oh=CCPo1h1^ake{500.0,500.0),
ou can implicitly animate a single layer property at a time, or many. ou can also implicitly animate several
layers simultaneously. The code in Listing 2 causes four implicit animations to occur simultaneously.
Listing 2 |mplicitly animating multiple properties of multiple layers
// ah1ma1e 1heLayeJ`s opac11y 1o 0 wh11e mov1hg 11
// 1uJ1heJ away 1h 1he 1ayeJ
1heLayeJ.opac11y=0.0,
1heLayeJ.zPos111oh=-100,
// ah1ma1e aho1heJLayeJ`s opac11y 1o 1
// wh11e mov1hg 11 c1oseJ 1h 1he 1ayeJ
aho1heJLayeJ.opac11y=1.0,
aho1heJLayeJ.zPos111oh=100.0,
|mplicit animations use the duration specified in the default animation for the property, unless the duration
has been overridden in an implicit or explicit transaction. See "Overriding the Duration of |mplied
Animations (page 48) for more information.
Animatien
|mplicit Animation
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
39
Lxplicit Animation
Core Animation also supports an explicit animation model. The explicit animation model requires that you
create an animation ob|ect, and set start and end values. An explicit animation won't start until you apply the
animation to a layer. The code fragment in Listing 3 creates an explicit animation that transitions a layer's
opacity fromfully opaque to fully transparent, and back over a 3 second duration. The animation doesn't begin
until it is added to the layer.
Listing 3 Lxplicit animation
CABas1cAh1ma11oh +1heAh1ma11oh,
1heAh1ma11oh=[CABas1cAh1ma11oh ah1ma11ohW11hKeyPa1h:_"opac11y"],
1heAh1ma11oh.duJa11oh=3.0,
1heAh1ma11oh.Jepea1Couh1=2,
1heAh1ma11oh.au1oJeveJses=YES,
1heAh1ma11oh.1Jomva1ue=[NSNumbeJ humbeJW11hF1oa1:1.0],
1heAh1ma11oh.1ova1ue=[NSNumbeJ humbeJW11hF1oa1:0.0],
[1heLayeJ addAh1ma11oh:1heAh1ma11oh 1oJKey:_"ah1ma1e0pac11y"],
Lxplicit animations are especially useful when creating animations that run continuously. Listing 4 shows how
to create an explicit animation that applies a Core|mage bloom filter to a layer, animating its intensity. This
causes the "selection layer to pulse, drawing the user's attention.
Listing 4 Continuous explicit animation example
// The se1ec11oh 1ayeJ w111 pu1se coh11huous1y.
// Th1s 1s accomp11shed by se111hg a b1oom 1111eJ oh 1he 1ayeJ
// cJea1e 1he 1111eJ ahd se1 11s de1au11 va1ues
CTF111eJ +1111eJ = [CTF111eJ 1111eJW11hName:_"CTB1oom"],
[1111eJ se10e1au11s],
[1111eJ se1va1ue:[NSNumbeJ humbeJW11hF1oa1:5.0] 1oJKey:_"1hpu1Rad1us"],
// hame 1he 1111eJ so we cah use 1he keypa1h 1o ah1ma1e 1he 1hpu1Th1ehs11y
// a11J1bu1e o1 1he 1111eJ
Animatien
Lxplicit Animation
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
40
[1111eJ se1Name:_"pu1seF111eJ"],
// se1 1he 1111eJ 1o 1he se1ec11oh 1ayeJ`s 1111eJs
[se1ec11ohLayeJ se1F111eJs:[NSAJJay aJJayW11h0bec1:1111eJ]],
// cJea1e 1he ah1ma11oh 1ha1 w111 hahd1e 1he pu1s1hg.
CABas1cAh1ma11oh+ pu1seAh1ma11oh = [CABas1cAh1ma11oh ah1ma11oh],
// 1he a11J1bu1e we wah1 1o ah1ma1e 1s 1he 1hpu1Th1ehs11y
// o1 1he pu1seF111eJ
pu1seAh1ma11oh.keyPa1h = _"1111eJs.pu1seF111eJ.1hpu1Th1ehs11y",
// we wah1 11 1o ah1ma1e 1Jom 1he va1ue 0 1o 1
pu1seAh1ma11oh.1Jomva1ue = [NSNumbeJ humbeJW11hF1oa1: 0.0],
pu1seAh1ma11oh.1ova1ue = [NSNumbeJ humbeJW11hF1oa1: 1.5],
// oveJ a ohe secohd duJa11oh, ahd Juh ah 1h11h11e
// humbeJ o1 11mes
pu1seAh1ma11oh.duJa11oh = 1.0,
pu1seAh1ma11oh.Jepea1Couh1 = hbCE_vALF,
// we wah1 11 1o 1ade oh, ahd 1ade o11, so 11 heeds 1o
// au1oma11ca11y au1oJeveJse.. 1h1s causes 1he 1h1ehs11y
// 1hpu1 1o go 1Jom 0 1o 1 1o 0
pu1seAh1ma11oh.au1oJeveJses = YES,
// use a 11m1hg cuJve o1 easy 1h, easy ou1..
pu1seAh1ma11oh.11m1hgFuhc11oh = [CA^ed1aT1m1hgFuhc11oh 1uhc11ohW11hName:
kCA^ed1aT1m1hgFuhc11ohEaseThEase0u1],
// add 1he ah1ma11oh 1o 1he se1ec11oh 1ayeJ. Th1s causes
// 11 1o beg1h ah1ma11hg. We`11 use pu1seAh1ma11oh as 1he
// ah1ma11oh key hame
[se1ec11ohLayeJ addAh1ma11oh:pu1seAh1ma11oh 1oJKey:_"pu1seAh1ma11oh"],
Animatien
Lxplicit Animation
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
41
Starting and Stopping Lxplicit Animations
ou start an explicit animation by sending a addAh1ma11oh:1oJKey: message to the target layer, passing
the animation and an identifier as parameters. Once added to the target layer the explicit animation will run
until the animation completes, or it is removed from the layer. The identifier used to add an animation to a
layer is also used to stop it by invoking JemoveAh1ma11ohFoJKey:. ou can stop all animations for a layer
by sending the layer a JemoveA11Ah1ma11ohs message.
Animatien
Starting and Stopping Lxplicit Animations
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
42
Layer actions are triggered in response to: layers being inserted and removed from the layer-tree, the value of
layer properties being modified, or explicit application requests. Typically, action triggers result in an animation
being displayed.
The Pole of Action Ob|ects
An action ob|ect is an ob|ect that responds to an action identifier via the CAAc11oh protocol. Action identifiers
are named using standard dot-separated key paths. A layer is responsible for mapping action identifiers to the
appropriate action ob|ect. when the action ob|ect for the identifier is located that ob|ect is sent the message
defined by the CAAc11oh protocol.
The CALayeJ class provides default action ob|ects-instances of CAAh1ma11oh, a CAAc11oh protocol compliant
class-for all animatable layer properties. CALayeJ also defines the following action triggers that are not linked
directly to properties, as well as the action identifiers in Table 1.
7abIe 1 Action triggers and their corresponding identifiers
Actien identifier 7rigger
The action identifier constant
kCA0h0JdeJTh.
A layer is inserted into a visible layer-tree, or the h1ddeh
property is set to N0.
The action identifier constant
kCA0h0JdeJ0u1.
A layer is removed from a visible layer-tree, or the
h1ddeh property is set to YES.
The action identifier constant
kCATJahs111oh.
A layer replaces an existing layer in a visible layer tree
using Jep1aceSub1ayeJ: w11h:.
Defined Search Pattern for Action Keys
when an action trigger occurs, the layer's ac11ohFoJKey: method is invoked. This method returns an action
ob|ect that corresponds to the action identifier passed as the parameter, or h11 if no action ob|ect exists.
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
43
Layer Actions
when the CALayeJ implementation of ac11ohFoJKey: is invoked for an identifier the following search
pattern is used:
1. |f the layer has a delegate, and it implements the method ac11ohFoJLayeJ:1oJKey: it is invoked,
passing the layer, and the action identifier as parameters. The delegate's ac11ohFoJLayeJ:1oJKey:
implementation should respond as follows:
Peturn NSNu11 if it doesn't handle the action identifier and the search should be terminated.
2. The layer's ac11ohs dictionary is searched for an ob|ect that corresponds to the action identifier.
3. The layer's s1y1e property is searched for an ac11ohs dictionary that contains the identifier.
4. The layer's class is sent a de1au11Ac11ohFoJKey: message. |t will return an action ob|ect corresponding
to the identifier, or h11 if not found.
Adopting the CAAction Protocol
The CAAc11oh protocol defines howaction ob|ects are invoked. Classes that implement the CAAc11oh protocol
have a method with the signature JuhAc11ohFoJKey:obec1:aJgumeh1s:.
when the action ob|ect receives the JuhAc11ohFoJKey:obec1:aJgumeh1s: message it is passed the
action identifier, the layer on which the action should occur, and an optional dictionary of parameters.
Typically, action ob|ects are an instance of a CAAh1ma11oh subclass, which implements the CAAc11oh protocol.
ou can, however, return an instance of any class that implements the protocol. when that instance receives
the JuhAc11ohFoJKey:obec1:aJgumeh1s: message it should respond by performing its action.
when an instance of CAAh1ma11oh receives the JuhAc11ohFoJKey:obec1:aJgumeh1s: message it
responds by adding itself to the layer's animations, causing the animation to run (see Listing 1 (page 44)).
Listing 1 runActionPorKey:ob|ect:arguments: implementation that initiates an animation
- {vo1d)JuhAc11ohFoJKey:{NSS1J1hg +)key
obec1:{1d)ah0bec1
aJgumeh1s:{NS01c11ohaJy +)d1c1
{
[{CALayeJ +)ah0bec1 addAh1ma11oh:se11 1oJKey:key],
Layer Actiens
Adopting the CAAction Protocol
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
44
]
Overriding an |mplied Animation
ou can provide a different implied animation for an action identifier by inserting an instance of CAAh1ma11oh
into the ac11ohs dictionary, into an actions dictionary in the s1y1e dictionary, by implementing the delegate
method ac11ohFoJLayeJ:1oJKey:, or subclassing a layer class, overriding de1au11Ac11ohFoJKey: and
returning the appropriate action ob|ect.
The example in Listing 2 replaces the default implied animation for the coh1eh1s property using delegation.
Listing 2 |mplied animation for the contents property
- {1d<CAAc11oh>)ac11ohFoJLayeJ:{CALayeJ +)1heLayeJ
1oJKey:{NSS1J1hg +)1heKey
{
CATJahs111oh +1heAh1ma11oh=h11,
11 {[1heKey 1sEqua1ToS1J1hg:_"coh1eh1s"])
{
1heAh1ma11oh = [[CATJahs111oh a11oc] 1h11],
1heAh1ma11oh.duJa11oh = 1.0,
1heAh1ma11oh.11m1hgFuhc11oh = [CA^ed1aT1m1hgFuhc11oh
1uhc11ohW11hName:kCA^ed1aT1m1hgFuhc11ohEaseTh],
1heAh1ma11oh.1ype = kCATJahs111ohPush,
1heAh1ma11oh.sub1ype = kCATJahs111ohFJomR1gh1,
]
Je1uJh 1heAh1ma11oh,
]
The example in Listing 3 (page 46) disables the default animation for the sub1ayeJs property using the
ac11ohs dictionary pattern.
Layer Actiens
Overriding an |mplied Animation
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
45
Listing 3 |mplied animation for the sublayers property
// ge1 a mu1ab1e veJs1oh o1 1he cuJJeh1 ac11ohs d1c11ohaJy
NS^u1ab1e01c11ohaJy +cus1omAc11ohs=[NS^u1ab1e01c11ohaJy
d1c11ohaJyW11h01c11ohaJy:[1heLayeJ ac11ohs]],
// add 1he hew ac11oh 1oJ sub1ayeJs
[cus1omAc11ohs se10bec1:[NSNu11 hu11] 1oJKey:_"sub1ayeJs"],
// se1 1heLayeJ ac11ohs 1o 1he upda1ed d1c11ohaJy
1heLayeJ.ac11ohs=cus1omAc11ohs,
Temporarily Disabling Actions
8y default, any time you change an animatable property, the appropriate animation will occur.
ou can temporarily disable actions when modifying layer properties by using transactions. See "Temporarily
Disabling Layer Actions (page 48) for more information.
Layer Actiens
Temporarily Disabling Actions
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
46
Lvery modification to a layer is part of a transaction. CATJahsac11oh is the Core Animation class responsible
for batching multiple layer-tree modifications into atomic updates to the render tree.
This chapter describes the two types of transactions Core Animation supports: implicit transactions and explicit
transactions.
|mplicit transactions
|mplicit transactions are created automatically when the layer tree is modified by a thread without an active
transaction, and are committed automatically when the thread's run-loop next iterates.
The example in Listing 1 modifies a layer's opac11y, zPos111oh, and pos111oh properties, relying on the
implicit transaction to ensure that the resulting animations occur at the same time.
Listing 1 Animation using an implicit transaction
1heLayeJ.opac11y=0.0,
1heLayeJ.zPos111oh=-200,
1he1ayeJ.pos111oh=CCPo1h1^ake{0.0,0.0),
Impertant: when modifying layer properties fromthreads that don't have a runloop, you must use explicit
transactions.
Lxplicit Transactions
ou create an explicit transaction by sending the CATJahsac11oh class a beg1h message before modifying
the layer tree, and a comm11 message afterwards. Lxplicit transactions are particularly useful when setting the
properties of many layers at the same time (for example, while laying out multiple layers), temporarily disabling
layer actions, or temporarily changing the duration of resulting implied animations.
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
47
Transactions
Temporarily Disabling Layer Actions
ou can temporarily disable layer actions when changing layer property values by setting the value of the
transaction's kCATJahsac11oh01sab1eAc11ohs to true. Any changes made during the scope of that
transaction will not result in an animation occurring. Listing 2 shows an example that disables the fade animation
that occurs when removing aLayeJ from a visible layer-tree.
Listing 2 Temporarily disabling a layer's actions
[CATJahsac11oh beg1h],
[CATJahsac11oh se1va1ue:{1d)kCFBoo1eahTJue
1oJKey:kCATJahsac11oh01sab1eAc11ohs],
[aLayeJ JemoveFJomSupeJ1ayeJ],
[CATJahsac11oh comm11],
Overriding the Duration of |mplied Animations
ou can temporarily alter the duration of animations that run in response to changing layer property values
by setting the value of the transaction's kCATJahsac11ohAh1ma11oh0uJa11oh key to a new duration. Any
resulting animations in that transaction scope will use that duration rather than their own. Listing 3 shows an
example that causes an animation to occur over 10 seconds rather than the duration specified by the zPos111oh
and opac11y animations..
Listing 3 Overriding the animation duration
[CATJahsac11oh beg1h],
[CATJahsac11oh se1va1ue:[NSNumbeJ humbeJW11hF1oa1:10.01]
1oJKey:kCATJahsac11ohAh1ma11oh0uJa11oh],
1heLayeJ.zPos111oh=200.0,
1heLayeJ.opac11y=0.0,
[CATJahsac11oh comm11],
Although the above example shows the duration bracketed by an explicit transaction beg1h and comm11, you
could omit those and use the implicit transaction instead.
7ransactiens
Lxplicit Transactions
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
48
Nesting Transactions
Lxplicit transactions can be nested, allowing you to disable actions for one part of an animation, or using
different durations for the implicit animations of properties that are modified. Only when the outer-most
transaction is committed will the animations occur.
Listing 4 shows an example of nesting two transactions. The outer transaction sets the implied animation
duration to 2 seconds and sets the layer's pos111oh property. The inner transaction sets the implied animation
duration to 5 seconds and changes the layer's opac11y and zPos111oh.
Listing 4 Nesting explicit transactions
[CATJahsac11oh beg1h], // ou1eJ 1Jahsac11oh
// chahge 1he ah1ma11oh duJa11oh 1o 2 secohds
[CATJahsac11oh se1va1ue:[NSNumbeJ humbeJW11hF1oa1:2.01]
1oJKey:kCATJahsac11ohAh1ma11oh0uJa11oh],
// move 1he 1ayeJ 1o a hew pos111oh
1heLayeJ.pos111oh = CCPo1h1^ake{0.0,0.0),
[CATJahsac11oh beg1h], // 1hheJ 1Jahsac11oh
// chahge 1he ah1ma11oh duJa11oh 1o 5 secohds
[CATJahsac11oh se1va1ue:[NSNumbeJ humbeJW11hF1oa1:5.01]
1oJKey:kCATJahsac11ohAh1ma11oh0uJa11oh],
// chahge 1he zPos111oh ahd opac11y
1heLayeJ.zPos111oh=200.0,
1heLayeJ.opac11y=0.0,
[CATJahsac11oh comm11], // 1hheJ 1Jahsac11oh
[CATJahsac11oh comm11], // ou1eJ 1Jahsac11oh
7ransactiens
Lxplicit Transactions
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
49
NSv1ew provides the classic "struts and springs" model of repositioning views relative to their superlayer when
it resizes. while layers support this model, Core Animation on OS X provides a more general layout manager
mechanism that allows developers to write their own layout managers. A custom layout manager (which
implements the CALayou1^ahageJ protocol) can be specified for a layer, which then assumes responsibility
for providing layout of the layer's sublayers.
This chapter describes the constraints layout manager and how to configure a set of constraints.
iDS Nete: The CALayeJ class in iOS only supports the "struts and springs positioning model, it
does not provide customlayout managers. However, if you want to manually position layers associated
with a particular view, you can override the 1ayou1Subv1ews method of that view and implement
your custom layout code there. Por more information on handling view-based layout in an iOS
application, see v|ew ltotomm|n Cu|Je lot |O5.
Constraints Layout Manager
Constraint-based layout allows you to specify the position and size of a layer using relationships between itself
its sibling layers or its superlayer. The relationships are represented by instances of the CACohs1Ja1h1 class
that are stored in an array in the sublayers' cohs1Ja1h1s property.
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
50
Laying Out Core Animation Layers
Pigure 1 shows the layout attributes you can use when specifying relationships.
Iigure 1 Constraint layout manager attributes
L$"$POTUSBJOU.BY:
L$"$POTUSBJOU.JO:
L$"$POTUSBJOU.JE:
L$"$POTUSBJOU.JO9
L$"$POTUSBJOU.BY9 L$"$POTUSBJOU.JE9
L$"$POTUSBJOU8JEUI
L$"$POTUSBJOU)FJHIU
when using constraints layout you first create an instance of CACohs1Ja1h1Layou1^ahageJ and set it as
the parent layer's layout manager. ou then create constraints for the sublayers by instantiating CACohs1Ja1h1
ob|ects and adding themto the sublayer's constraints using addCohs1Ja1h1:. Lach CACohs1Ja1h1 instance
encapsulates one geometry relationship between two layers on the same axis.
Sibling layers are referenced by name, using the hame property of a layer. The special name supeJ1ayeJ is
used to refer to the layer's superlayer.
A maximum of two relationships must be specified per axis. |f you specify constraints for the left and right
edges of a layer, the width will vary. |f you specify constraints for the left edge and the width, the right edge
of the layer will move relative to the superlayer's frame. Often you'll specify only a single edge constraint, the
layer's size in the same axis will be used as the second relationship.
Laying Dut Cere Animatien Layers
Constraints Layout Manager
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
51
The example code in Listing 1 creates a layer, and then adds sublayers that are positioned using constraints.
Pigure 2 shows the resulting layout.
Iigure 2 Lxample constraints based layout
UIF-BZFS
MBZFS"
MBZFS#
Listing 1 Configuring a layer's constraints
// cJea1e ahd se1 a cohs1Ja1h1 1ayou1 mahageJ 1oJ 1heLayeJ
1heLayeJ.1ayou1^ahageJ=[CACohs1Ja1h1Layou1^ahageJ 1ayou1^ahageJ],
CALayeJ +1ayeJA = [CALayeJ 1ayeJ],
1ayeJA.hame = _"1ayeJA",
1ayeJA.bouhds = CCRec1^ake{0.0,0.0,100.0,25.0),
1ayeJA.boJdeJW1d1h = 2.0,
[1ayeJA addCohs1Ja1h1:[CACohs1Ja1h1 cohs1Ja1h1W11hA11J1bu1e:kCACohs1Ja1h1^1dY
Je1a11veTo:_"supeJ1ayeJ"
a11J1bu1e:kCACohs1Ja1h1^1dY]],
[1ayeJA addCohs1Ja1h1:[CACohs1Ja1h1 cohs1Ja1h1W11hA11J1bu1e:kCACohs1Ja1h1^1dX
Je1a11veTo:_"supeJ1ayeJ"
a11J1bu1e:kCACohs1Ja1h1^1dX]],
[1heLayeJ addSub1ayeJ:1ayeJA],
Laying Dut Cere Animatien Layers
Constraints Layout Manager
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
52
CALayeJ +1ayeJB = [CALayeJ 1ayeJ],
1ayeJB.hame = _"1ayeJB",
1ayeJB.boJdeJW1d1h = 2.0,
[1ayeJB addCohs1Ja1h1:[CACohs1Ja1h1 cohs1Ja1h1W11hA11J1bu1e:kCACohs1Ja1h1W1d1h
Je1a11veTo:_"1ayeJA"
a11J1bu1e:kCACohs1Ja1h1W1d1h]],
[1ayeJB addCohs1Ja1h1:[CACohs1Ja1h1 cohs1Ja1h1W11hA11J1bu1e:kCACohs1Ja1h1^1dX
Je1a11veTo:_"1ayeJA"
a11J1bu1e:kCACohs1Ja1h1^1dX]],
[1ayeJB addCohs1Ja1h1:[CACohs1Ja1h1 cohs1Ja1h1W11hA11J1bu1e:kCACohs1Ja1h1^axY
Je1a11veTo:_"1ayeJA"
a11J1bu1e:kCACohs1Ja1h1^1hY
o11se1:-10.0]],
[1ayeJB addCohs1Ja1h1:[CACohs1Ja1h1 cohs1Ja1h1W11hA11J1bu1e:kCACohs1Ja1h1^1hY
Je1a11veTo:_"supeJ1ayeJ"
a11J1bu1e:kCACohs1Ja1h1^1hY
o11se1:+10.0]],
[1heLayeJ addSub1ayeJ:1ayeJB],
Here's what the code does:
1. Creates an instance of CACohs1Ja1h1Layou1^ahageJ and sets it as the 1ayou1^ahageJ property of
1heLayeJ.
2. Creates an instance of CALayeJ (1ayeJA) and sets the layer's hame property to "layerA.
3. The bounds of 1ayeJA is set to a (0.0,0.0,100.0,25.0).
4. Creates a CACohs1Ja1h1 ob|ect, and adds it as a constraint of 1ayeJA.
This constraint aligns the horizontal center of 1ayeJA with the horizontal center of the superlayer.
5. Creates a second CACohs1Ja1h1 ob|ect, and adds it as a constraint of 1ayeJA.
Laying Dut Cere Animatien Layers
Constraints Layout Manager
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
53
This constraint aligns the vertical center of 1ayeJA with the vertical center of the superlayer.
6. Adds 1ayeJA as a sublayer of 1heLayeJ.
7. Creates an instance of CALayeJ (1ayeJB) and sets the layer's hame property to "layer8.
8. Creates a CACohs1Ja1h1 ob|ect, and adds it as a constraint of 1ayeJA.
This constraint sets the width of 1ayeJB to the width of 1ayeJA.
9. Creates a second CACohs1Ja1h1 ob|ect, and adds it as a constraint of 1ayeJB.
This constraint sets the horizontal center of 1ayeJB to be the same as the horizontal center of 1ayeJA.
10. Creates a third CACohs1Ja1h1 ob|ect, and adds it as a constraint of 1ayeJB.
This constraint sets the top edge of 1ayeJB 10 points below the bottom edge of 1ayeJA.
11. Creates a fourth CACohs1Ja1h1 ob|ect, and adds it as a constraint of 1ayeJB.
This constraint sets the bottom edge of 1ayeJB 10 points above the bottom edge of the superlayer.
Warning: |t is possible to create constraints that result in circular references to the same attributes.
|n cases where the layout is unable to be computed, the behavior is undefined.
Laying Dut Cere Animatien Layers
Constraints Layout Manager
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
54
The CAAh1ma11oh and CALayeJ classes extend the NSKeyva1ueCod1hg protocol adding default values for
keys, expanded wrapping conventions, and key path support for CCPo1h1, CCRec1, CCS1ze, and
CATJahs1oJm30.
Key-value Coding Compliant Container Classes
8oth CALayeJ and CAAh1ma11oh are key-value coding compliant container classes, allowing you to set values
for arbitrary keys. That is, while the key "someKey is not a declared property of the CALayeJ class, however
you can still set a value for the key "someKey as follows:
[1heLayeJ se1va1ue:[NSNumbeJ humbeJW11hTh1egeJ:50] 1oJKey:_"someKey"],
ou retrieve the value for the key "someKey using the following code:
someKeyva1ue=[1heLayeJ va1ueFoJKey:_"someKey"],
DS X Nete: On OS X, the CALayeJ and CAAh1ma11oh classes support the NSCod1hg protocol and
will automatically archive any additional keys that you set for an instance of those classes.
Default value Support
Core Animation adds a new convention to key value coding that allows a class to provide a default value that
is used when a class has no value set for that key. 8oth CALayeJ or CAAh1ma11oh support this convention
using the class method de1au11va1ueFoJKey:.
To provide a default value for a key you create a subclass of the class and override de1au11va1ueFoJKey:.
The subclass implementation examines the key parameter and then returns the appropriate default value.
Listing 1 shows an example implementation of de1au11va1ueFoJKey: that provides a new default value for
the layer property masksToBouhds.
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
55
Core Animation Lxtensions To Key-value Coding
Listing 1 Lxample implementation of defaultvaluePorKey:
+ {1d)de1au11va1ueFoJKey:{NSS1J1hg +)key
{
11 {[key 1sEqua1ToS1J1hg:_"masksToBouhds"])
Je1uJh [NSNumbeJ humbeJW11hBoo1:YES],
Je1uJh [supeJ de1au11va1ueFoJKey:key],
]
wrapping Conventions
when using the key-value coding methods to access properties whose values are not ob|ects the standard
key-value coding wrapping conventions support, the following wrapping conventions are used:
CIass C 7ype
NSva1ue CCPo1h1
NSva1ue CCS1ze
NSva1ue CCRec1
NSA111heTJahs1oJm (OS X only) CCA111heTJahs1oJm
NSva1ue CATransform3D
Key Path Support for Structure Pields
CAAh1ma11oh provides support for accessing the fields of selected structures using key paths. This is useful
for specifying these structure fields as the key paths for animations, as well as setting and getting values using
se1va1ue:1oJKeyPa1h: and va1ueFoJKeyPa1h:.
CATJahs1oJm30 exposes the following fields:
Descriptien Structure IieId
The rotation, in radians, in the x axis. Jo1a11oh.x
Cere Animatien xtensiens 7e key-VaIue Ceding
wrapping Conventions
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
56
Descriptien Structure IieId
The rotation, in radians, in the y axis. Jo1a11oh.y
The rotation, in radians, in the z axis. Jo1a11oh.z
The rotation, in radians, in the z axis. This is identical to setting the Jo1a11oh.z
field.
Jo1a11oh
Scale factor for the x axis. sca1e.x
Scale factor for the y axis. sca1e.y
Scale factor for the z axis. sca1e.z
Average of all three scale factors. sca1e
Translate in the x axis. 1Jahs1a11oh.x
Translate in the y axis. 1Jahs1a11oh.y
Translate in the z axis. 1Jahs1a11oh.z
Translate in the x and y axis. value is an NSSize or CCSize. 1Jahs1a11oh
CCPo1h1 exposes the following fields:
Descriptien Structure IieId
The x component of the point. x
The y component of the point. y
CCS1ze exposes the following fields:
Descriptien Structure IieId
The width component of the size. w1d1h
The height component of the size. he1gh1
CCRec1 exposes the following fields:
Descriptien Structure IieId
The origin of the rectangle as a CCPo1h1. oJ1g1h
Cere Animatien xtensiens 7e key-VaIue Ceding
Key Path Support for Structure Pields
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
57
Descriptien Structure IieId
The x component of the rectangle origin. oJ1g1h.x
The y component of the rectangle origin. oJ1g1h.y
The size of the rectangle as a CCS1ze. s1ze
The width component of the rectangle size. s1ze.w1d1h
The height component of the rectangle size. s1ze.he1gh1
ou can not specify a structure field key path using Ob|ective-C 2.0 properties. This will not work:
myLayeJ.1Jahs1oJm.Jo1a11oh.x=0,
|nstead you must use se1va1ue:1oJKeyPa1h: or va1ueFoJKeyPa1h: as shown below:
[myLayeJ se1va1ue:[NSNumbeJ humbeJW11hTh1:0] 1oJKeyPa1h:_"1Jahs1oJm.Jo1a11oh.x"],
Cere Animatien xtensiens 7e key-VaIue Ceding
Key Path Support for Structure Pields
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
58
Pegardless of the type of media a layer displays, a layer's style properties are applied by the render-tree as it
composites layers.
This chapter describes the layer style properties and provides examples of their effect on an example layer.
Nete: The layer style properties available on OS X and iOS differ and are noted below.
Ceometry Properties
A layer's geometry properties specify howit is displayed relative to its parent layer. The geometry also specifies
the radius used to round the layer corners and a transform that is applied to the layer and its sublayers.
Pigure 1 shows the geometry of the example layer.
Iigure 1 Layer geometry
The following CALayeJ properties specify a layer's geometry:
1Jame
bouhds
pos111oh
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
59
Layer Style Properties
ahchoJPo1h1
coJheJRad1us
1Jahs1oJm
zPos111oh
iDS Nete: The coJheJRad1us property is supported only in iOS 3.0 and later.
8ackground Properties
Next, the layer renders its background. ou can define a color for the background as well as a Core |mage filter.
Pigure 2 illustrates the sample layer with its backgJouhdCo1oJ set.
Iigure 2 Layer with background color
The background filter is applied to the content behind the layer. Por example, you may wish to apply a blur
filter as a background filter to make the layer content stand out better.
The following CALayeJ properties affect the display of a layer's background:
backgJouhdCo1oJ
backgJouhdF111eJs
Layer StyIe Preperties
8ackground Properties
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
60
iDS Nete: while the CALayeJ class in iOS exposes the backgJouhdCo1oJ property, Core |mage is
not available. The filters available for this property are currently undefined.
Layer Content
Next, if set, the content of the layer is rendered. The layer content can be created using the uartz graphics
environment, OpenCL, uickTime, or uartz Composer.
Pigure 4 shows the example layer with its content composited.
Iigure 3 Layer displaying a content image
8y default, the content of a layer is not clipped to its bounds and corner radius. The masksToBouhds property
can be set to 1Jue to clip the layer content to those values.
The following CALayeJ properties affect the display of a layer's content:
coh1eh1s
coh1eh1sCJav11y
Layer StyIe Preperties
Layer Content
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
61
Sublayers Content
|t is typical that a layer will have a hierarchy of child layers, its sublayers. These sublayers are rendered recursively,
relative to the parent layer's geometry. The parent layer's sub1ayeJTJahs1oJm is applied to each sublayer,
relative to the parent layer's anchor point.
Iigure 4 Layer displaying the sublayers content
8y default, a layer's sublayers are not clipped to the layer's bounds and corner radius. The masksToBouhds
property can be set to 1Jue to clip the layer content to those values. The example layer's maskToBouhds
property is 1a1se, notice that the sublayer displaying the monitor and test pattern is partially outside of its
parent layer's bounds.
The following CALayeJ properties affect the display of a layer's sublayers:
sub1ayeJs
masksToBouhds
sub1ayeJTJahs1oJm
Layer StyIe Preperties
Sublayers Content
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
62
8order Attributes
A layer can display an optional border using a specified color and width. Pigure 5 shows the example layer
after applying a border.
Iigure 5 Layer displaying the border attributes content
The following CALayeJ properties affect the display of a layer's borders:
boJdeJCo1oJ
boJdeJW1d1h
Layer StyIe Preperties
8order Attributes
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
63
iDS Nete: The boJdeJCo1oJ and boJdeJW1d1h properties are supported only in iOS 3.0 and later.
Pilters Property
An array of Core |mage filters can be applied to the layer. These filters affect the layer's border, content, and
background. Pigure 6 shows the example layer with the Core |mage posterize filter applied.
Iigure 6 Layer displaying the filters properties
The following CALayeJ property specifies a layers content filters:
1111eJs
Layer StyIe Preperties
Pilters Property
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
64
iDS Nete: while the CALayeJ class in iOS exposes the 1111eJs property, Core |mage is not available.
Currently the filters available for this property are undefined.
Shadow Properties
Optionally, a layer can display a shadow, specifying its opacity, color, offset, and blur radius. Pigure 7 shows
the example layer with a red shadow applied.
Iigure 7 Layer displaying the shadow properties
The following CALayeJ properties affect the display of a layer's shadow:
shadowCo1oJ
shadow011se1
shadow0pac11y
shadowRad1us
Layer StyIe Preperties
Shadow Properties
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
65
iDS Nete: The shadowCo1oJ, shadow011se1, shadow0pac11y, and shadowRad1us properties
are supported only in iOS 3.2 and later.
Opacity Property
8y setting the opacity of a layer, you can control the layer's transparency. Pigure 8 shows the example layer
with an opacity of 0.5.
Iigure 8 Layer including the opacity property
The following CALayeJ property specifies the opacity of a layer:
opac11y
Layer StyIe Preperties
Opacity Property
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
66
Composite Property
A layer's compositing filter is used to combine the layer content with the layers behind it. 8y default, a layer
is composited using source-over. Pigure 9 shows the example layer with a compositing filter applied.
Iigure 9 Layer composited using the compositingPilter property
The following CALayeJ property specifies the composting filter for a layer:
compos111hgF111eJ
Layer StyIe Preperties
Composite Property
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
67
iDS Nete: while the CALayeJ class in iOS exposes the compos111hgF111eJ property, Core |mage
is not available. Currently the filters available for this property are undefined.
Mask Properties
Pinally, you can specify a layer that will serve as a mask, further modifying how the rendered layer appears.
The opacity of the mask layer determines masking when the layer is composited. Pigure 10 shows the example
layer composited with a mask layer.
Iigure 10 Layer composited with the mask property
The following CALayeJ property specifies the mask for a layer:
mask
iDS Nete: The mask property is supported only in iOS 3.0 and later.
Layer StyIe Preperties
Mask Properties
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
68
The Core Animation Kiosk Style Menu example displays a simple selection example using Core Animation
layers to generate and animate the user interface. |n less than 100 lines of code, it demonstrates the following
capabilities and design patterns:
Handling key events through the Menuview instance that hosts the view.
This application makes heavy use of Core |mage filters and uartz Composer compositions and, as a result,
runs only on OS X. The techniques illustrated for managing the layer hierarchy, implicit and explicit animation,
and event handling are common to both platforms.
The application is available as sample code in two versions: One that uses the 0CCompos111ohLayeJ as the
background and a second that uses a solid black background. See the CoteAn|mot|onl|osl5tyleVenu sample
for a working copy of the application. The initial code walkthrough describes the version of the application
that uses the uartz Composer background. The performance increase when using a solid color is discussed
later in the article.
The User |nterface
The CCereAnimatienkieskMenuStyIe sample provides a very basic kiosk-style user interface, it takes over
the entire screen and the user can select a single item in a menu. The user navigates the menu using the up
and down arrows on the keyboard. As the selection changes the selection indicator (the rounded white
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
69
Lxample: Core Animation Kiosk Menu Style
Application
rectangle) animates to its new location. A continuously animating bloom filter is set for the selection indicator
causing it to subtly catch your attention. The background is a uartz Composer animation runs continuously,
providing an attention grabbing background. Pigure 1 shows the application's interface.
Iigure 1 Core Animation Kiosk Menu |nterface
See the HTML version of this
document to view the video.
See the HTML version of this
document to view the video.
Lxamining the Nib Pile
The Layer Hierarchy
The layer hierarchy, also referred to as the layer tree, of the CoreAnimationKioskMenuStyle application is shown
below.
Iigure 2 Layer Hierarchy Por CCoreAnimationKioskStyleMenu Application
Movies (CATextLayer)
Music (CATextLayer)
Podcasts (CATextLayer)
Photos (CATextLayer)
Internet (CATextLayer)
menuLayer (CALayer)
selectionLayer (CALayer)
rootLayer (QCComposerLayer)
The Joo1LayeJ is an instance of 0CComposeJLayeJ. As the root-layer this layer is the same size as the
^ehuv1ew instance, and remains that way as the window is resized.
The mehuLayeJ is a sublayer of the Joo1LayeJ. |t is an empty layer, it does not have anything set as its
coh1eh1s property and none of its style properties are set. The mehusLayeJ is simply used as a container for
the menu itemlayers. This approach allows the application to easily access a menu itemsublayer by its position
in the mehusLayeJs.sub1ayeJs array. The mehusLayeJ is the same size as, and overlaps, the Joo1LayeJ.
This was done intentionally so that there was no need to convert between coordinate systems when positioning
the se1ec11ohLayeJ relative to the current menu item.
xampIe: Cere Animatien kiesk Menu StyIe AppIicatien
The User |nterface
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
70
Lxamining the Application's Nib
^a1h^ehu.h1b is very straightforward. An instance of Cus1omv1ew is dragged from the |nterface 8uilder
palette and positioned in the window. |t is resized such that it fills the entire window. The Se1ec11ohv1ew.h
file is imported into |nterface 8uilder by dragging it to the Menu.nib window. The Cus1omv1ew is then selected
in the Selection view |dentity palette, and the Class is changed to Se1ec11ohv1ew.
Iigure 3 MainMenu.nib Pile
No other connections need to be made. when the nib file is loaded the window is unarchived along with the
Se1ec11ohv1ew instance. The Se1ec11ohv1ew class layers are configured in the class's implementation of
awakeFJomN1b.
xampIe: Cere Animatien kiesk Menu StyIe AppIicatien
Lxamining the Application's Nib
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
71
Lxamining the Application's Code
Having looked at the application's nib file and the overall design, you can now begin examining the
implementation of the Se1ec11ohv1ew class. The Se1ec11ohv1ew.h file declares the properties and methods
for the Se1ec11ohv1ew, Selectionview.m contains the implementation. |n order to find the code snippets
easier in the implementation file, #pJagma maJk statements have been added that correspond to each listing.
CCoreAnimationKioskStyleMenu.h and CCoreAnimationKioskStyleMenu.m
Piles
The CodeAh1ma11ohK1osk^ehuApp0e1ega1e.hand.mfiles were createdautomatically whenthe application
was created. They contain no code of relevance to this example.
Lxamining Selectionview.h
The Se1ec11ohv1ew class is a subclass of NSv1ew. |t declares four properties as well as the methods the
Se1ec11ohv1ew.h implements. |t is the only view in the application's window and serves as the container
for the Joo1LayeJ and the other layers in the applications layer tree.
Listing 1 Selectionview.h Pile Listing
#1mpoJ1 <Cocoa/Cocoa.h>
#1mpoJ1 <0uaJ1zCoJe/0uaJ1z.h>
// The Se1ec11ohv1ew c1ass 1s 1he v1ew subc1ass 1ha1 1s 1hseJ1ed 1h1o
// 1he w1hdow. T1 hos1s 1he Joo1LayeJ, ahd Jespohds 1o eveh1s.
_1h1eJ1ace Se1ec11ohv1ew : NSv1ew {
// Coh1a1hs 1he se1ec1ed mehu 11em 1hdex
NSTh1egeJ se1ec1edThdex,
// The 1ayeJ 1ha1 coh1a1hs 1he mehu 11em 1ayeJs
CALayeJ +mehuLayeJ,
// The 1ayeJ 1ha1 1s d1sp1ays 1he se1ec11oh
CALayeJ +se1ec11ohLayeJ,
xampIe: Cere Animatien kiesk Menu StyIe AppIicatien
Lxamining the Application's Code
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
72
// The aJJay o1 1ayeJs 1ha1 coh1a1h 1he mehu 11em hames.
NSAJJay +hames,
]
_pJopeJ1y NSTh1egeJ se1ec1edThdex,
_pJopeJ1y {Je1a1h) CALayeJ +mehuLayeJ,
_pJopeJ1y {Je1a1h) CALayeJ +se1ec11ohLayeJ,
_pJopeJ1y {Je1a1h) NSAJJay +hames,
-{vo1d)awakeFJomN1b,
-{vo1d)se1upLayeJs,
-{vo1d)chahgeSe1ec1edThdex:{NSTh1egeJ)1heSe1ec1edThdex,
-{vo1d)movebp:{1d)sehdeJ,
-{vo1d)move0owh:{1d)sehdeJ,
-{vo1d)dea11oc,
_ehd
Nete: Notice that 0uaJ1z/CoJeAh1ma11oh.h is imported. The 0uaJ1zCoJe.1JamewoJk must
be added to any pro|ect that uses Core Animation. 8ecause this example uses uartz Composer the
Se1ec11ohv1ew.h header also imports 0uaJ1z/0uaJ1z.h, and the 0uaJ1z.1JamewoJk is added
to the pro|ect.
Lxamining Selectionview.m
The Se1ec11ohv1ew class is the workhorse of this application. |t responds when the view is loaded by the
nib, expands to fill the current screen, sets up the layers to be displayed, creates the animations, and handles
the keys that move the selection.
The listing of the Se1ec11ohv1ew.m file is divided as follows:
Cleaning Up
|mplementing awakePromNib
The awakeFJomN1b method is called when ^a1h^ehu.h1b is loaded and unarchived. The view is expected
to complete its setup in awakeFJomN1b.
The ^a1h^ehuv1ew implementation of awakeFJomN1bdoes the following:
Creates an array of strings, the names, which are used to display the menu items.
Hides the cursor. Pull screen applications typically don't showthe cursor and this application relies entirely
on keyboard input.
The view is resized to automatically fill the screen in which the window resizes. This gives the kiosk look.
Makes the window the view resides within the firstPesponder so that it receives the up and down arrow
events.
Calls the se1upLayeJs method to setup the layers (discussed in "The setupLayers Method (page 75)
The Joo1LayeJ is created and set for the view and only then layers are enabled for the view. Doing this
in this order causes the view to use the specified layer, rather than creating it's own layer, this is referred
to as Iayer-view besting. Layer-view hosting requires that all drawing be the responsibility of Core
Animation. ou must not use the NSv1ew drawing capabilities and methods, however the view
event-handling routines are used as normal.
The other is related to performance. Depending upon the hardware, running a uartz Composer animation
in the background can cause performance issues. Using a solid color performance can be increased. This
is further discussed in "Performance Considerations (page 81).
Listing 3 Configuration of the 8ackground rootLayer
#pJagma maJk L1s11hg: "Coh11guJa11oh o1 1he BackgJouhd Joo1LayeJ"
-{vo1d)se1upLayeJs,
{
xampIe: Cere Animatien kiesk Menu StyIe AppIicatien
Lxamining the Application's Code
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
75
// make a 0uaJ1z Compos111oh LayeJ.
// No1e: Ruhh1hg a 0CCompos111oh cah s1gh111cah11y 1mpac1 peJ1oJmahce
0CCompos111ohLayeJ+ Joo1LayeJ=[0CCompos111ohLayeJ compos111ohLayeJW11hF11e:
[[NSBuhd1e ma1hBuhd1e] pa1hFoJResouJce:_"BackgJouhd" o1Type:_"q1z"]],
// Se1 1he 0CCompos111ohLayeJ as 1he Joo1 1ayeJ
// ahd 1heh 1uJh oh wah1sLayeJ. Th1s oJdeJ cases
// 1ayeJ-hos11hg behav1oJ oh 1he paJ1 o1 1he v1ew..
[se11 se1LayeJ:Joo1LayeJ],
[se11 se1Wah1sLayeJ:YES],
The #pJagma maJk Se1up mehuLayeJs AJJay. The Se1ec1ab1e ^ehu T1ems. is shown in Listing
4 (page 76). This code initialized the mehuLayeJ of the application inserting it as a sublayer of the Joo1LayeJ
(see Pigure 2 (page 70) for a reminder of the layer hierarchy of the application. |t then inserts separate layers
for each text entry into the mehuLayeJ. This code is located at #pJagma maJk - Se1up mehuLayeJs
AJJay. The Se1ec1ab1e ^ehu T1ems. in the sample.
Listing 4 Setup menuLayers Array. The Selectable Menu |tems.
// CJea1e a 1ayeJ 1o coh1a1h 1he mehus
se11.mehuLayeJ=[CALayeJ 1ayeJ] ,
se11.mehuLayeJ.1Jame=Joo1LayeJ.1Jame,
se11.mehuLayeJ.1ayou1^ahageJ=[CACohs1Ja1h1Layou1^ahageJ 1ayou1^ahageJ],
[Joo1LayeJ addSub1ayeJ:se11.mehuLayeJ],
// se1up ahd ca1cu1a1e 1he s1ze ahd 1oca11oh o1 1he 1hd1v1dua11y se1ec1ab1e
11ems.
CCF1oa1 w1d1h=400.0,
CCF1oa1 he1gh1=50.0,
CCF1oa1 spac1hg=20.0,
CCF1oa1 1oh1S1ze=32.0,
CCF1oa1 1h111a1011se1=se11.bouhds.s1ze.he1gh1/2-{he1gh1+5+spac1hg+4)/2.0,
//CJea1e wh11eCo1oJ 11`s used 1o dJaw 1he 1ex1 ahd a1so 1h 1he se1ec11ohLayeJ
CCCo1oJRe1 wh11eCo1oJ=CCCo1oJCJea1eCeheJ1cRCB{1.01,1.01,1.01,1.01),
xampIe: Cere Animatien kiesk Menu StyIe AppIicatien
Lxamining the Application's Code
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
76
// T1eJa1e oveJ 1he 11s1 o1 se1ec11oh hames ahd cJea1e 1ayeJs 1oJ each.
// The mehuT1emLayeJ`s aJe a1so pos111ohed duJ1hg 1h1s 1oop.
NSTh1egeJ 1,
1oJ {1=0,1<[hames couh1],1++) {
CATex1LayeJ +mehuT1emLayeJ=[CATex1LayeJ 1ayeJ],
mehuT1emLayeJ.s1J1hg=[se11.hames obec1A1Thdex:1],
mehuT1emLayeJ.1oh1=_"Luc1da-CJahde",
mehuT1emLayeJ.1oh1S1ze=1oh1S1ze,
mehuT1emLayeJ.1oJegJouhdCo1oJ=wh11eCo1oJ,
[mehuT1emLayeJ addCohs1Ja1h1:[CACohs1Ja1h1
cohs1Ja1h1W11hA11J1bu1e:kCACohs1Ja1h1^axY
Je1a11veTo:_"supeJ1ayeJ"
a11J1bu1e:kCACohs1Ja1h1^axY
o11se1:-{1+he1gh1+spac1hg+1h111a1011se1)]],
[mehuT1emLayeJ addCohs1Ja1h1:[CACohs1Ja1h1
cohs1Ja1h1W11hA11J1bu1e:kCACohs1Ja1h1^1dX
Je1a11veTo:_"supeJ1ayeJ"
a11J1bu1e:kCACohs1Ja1h1^1dX]],
[se11.mehuLayeJ addSub1ayeJ:mehuT1emLayeJ],
] // ehd o1 1oJ 1oop
[se11.mehuLayeJ 1ayou1T1Needed],
The #pJagma maJk Se1up se1ec11ohLayeJ. bsed 1o 01sp1ay 1he CuJJeh11y Se1ec1ed T1em.
is shown in Listing 5 (page 78). The code is commented, but to summarize:
A CTB1oom filter is added to the layer and configured to continuously provide a pulsing animation to the
selection indicator.
ahchoJPo1h1
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
backgJouhdCo1oJ
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84). {subpJopeJ11es aJe
ah1ma1ed us1hg a bas1c ah1ma11oh)
backgJouhdF111eJs
Uses the default implied CATJahs111ohAh1ma11oh described in Table 2 (page 84). Sub-properties of
the filters are animated using the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
boJdeJCo1oJ
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
boJdeJW1d1h
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
bouhds
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
compos111hgF111eJ
Uses the default implied CATJahs111ohAh1ma11oh described in Table 2 (page 84). Sub-properties of
the filters are animated using the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
coh1eh1s
coh1eh1sRec1
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
coJheJRad1us
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
82
Animatable Properties
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
doub1eS1ded
No default implied animation is set.
1111eJs
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84). Sub-properties of the filters
are animated using the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
1Jame
The frame property itself is not animatable. ou can achieve the same results by modifying the bouhds
and pos111oh properties instead.
h1ddeh
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
mask
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
masksToBouhds
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
opac11y
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
pos111oh
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
shadowCo1oJ
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
shadow011se1
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
shadow0pac11y
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
shadowRad1us
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
sub1ayeJs
Uses the default implied CATJahs111ohAh1ma11oh described in Table 2 (page 84).
sub1ayeJTJahs1oJm
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
AnimatabIe Preperties
CALayer Animatable Properties
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
83
1Jahs1oJm
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
zPos111oh
Uses the default implied CABas1cAh1ma11oh described in Table 1 (page 84).
7abIe 1 Default |mplied 8asic Animation
VaIue Descriptien
CA8asicAnimation Class
.25 seconds, or the duration of the current transaction duJa11oh
Dependent on layer property type keyPath
7abIe 2 Default |mplied Transition
VaIue Descriptien
CATransition Class
.25 seconds, or the duration of the current transaction duration
Pade (kCATJahs111ohFade) type
0.0 startProgress
1.0 endProgress
C|Pilter Animatable Properties
Core Animation adds the following animatable properties to Core |mage's CTF111eJ class. See CTF111eJ
CoJe Ah1ma11oh Add111ohs for more information. These properties are available only on OS X.
hame
ehab1ed
AnimatabIe Preperties
C|Pilter Animatable Properties
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
84
This table describes the changes to Cote An|mot|on ltotomm|n Cu|Je .
Netes Date
Updated the document to reflect Core Animation support in iOS 4.2. 2010-09-24
Corrected iOS origin information. Clarified that the coordinate system
origin used in the examples are based on the OS X model.
2010-08-12
Corrected autoresizing masks table. 2010-05-25
Added missing constant to the contentCravity property resizing table in
Providing Layer Content.
2010-03-24
Updated Core Animation Kiosk Style Menu tutorial pro|ect. 2010-02-24
Updated infinite value for repeatCount. 2010-01-20
Modified section headings. 2009-10-19
Corrected availability of cornerPadius on iOS v 3.0 and later. 2009-08-13
|ntroduces iOS SDK content to OS X content. Corrects frame animation
capabilities.
2008-11-13
Corrected typos. 2008-09-09
Updated for iOS. 2008-06-18
Corrected typos. 2008-05-06
Corrected typos. 2008-03-11
Corrected typos. Corrected PadiansToDegrees() calculation. 2008-02-08
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
85
Document Pevision History
Netes Date
Corrected typos. 2007-12-11
Added information on the presentation tree. Added example application
walkthough.
2007-10-31
New document that introduces the main components and services of
Core Animation.
Added "Key-value Coding Additions chapter.
Updated class names to reflect new Core Animation AP| prefix.
Decument Revisien Histery
2010-09-24 | 2010 Apple |nc. All Pights Peserved.
86
Apple |nc.
2010 Apple |nc.
All rights reserved.
No part of this publication may be reproduced,
stored in a retrieval system, or transmitted, in any
form or by any means, mechanical, electronic,
photocopying, recording, or otherwise, without
prior written permission of Apple |nc., with the
following exceptions: Any person is hereby
authorized to store documentation on a single
computer for personal use only and to print
copies of documentation for personal use
provided that the documentation contains
Apple's copyright notice.
No licenses, express or implied, are granted with
respect to any of the technology described in this
document. Apple retains all intellectual property
rights associated with the technology described
in this document. This document is intended to
assist application developers to develop
applications only for Apple-labeled computers.
Apple |nc.
1 |nfinite Loop
Cupertino, CA 95014
408-996-1010
Apple, the Apple logo, Cocoa, Cocoa Touch,
iPhone, iPod, iPod touch, Mac, Ob|ective-C, OS X,
uartz, and uickTime are trademarks of Apple
|nc., registered in the U.S. and other countries.
OpenCL is a registered trademark of Silicon
Craphics, |nc.
iOS is a trademark or registered trademark of
Cisco in the U.S. and other countries and is used
under license.
ven tbeugb AppIe bas reviewed tbis decument,
APPL MAkS ND WARRAN7 DR RPRSN7A7IDN,
I7HR XPRSS DR IMPLID, WI7H RSPC7 7D 7HIS
DDCUMN7, I7S UALI7, ACCURAC,
MRCHAN7A8ILI7, DR II7NSS IDR A PAR7ICULAR
PURPDS. ASARSUL7, 7HISDDCUMN7ISPRDVIDD
AS IS, AND DU, 7H RADR, AR ASSUMINC 7H
N7IR RISk AS 7D I7S UALI7 AND ACCURAC.
IN ND VN7 WILL APPL 8 LIA8L IDR DIRC7,
INDIRC7, SPCIAL, INCIDN7AL, DRCDNSUN7IAL
DAMACS RSUL7INC IRDM AN DIC7 DR
INACCURAC IN 7HIS DDCUMN7, even if advised ef
tbe pessibiIity ef sucb damages.
7H WARRAN7 AND RMDIS S7 IDR7H A8DV
AR XCLUSIV AND IN LIU DI ALL D7HRS, DRAL
DR WRI77N, XPRSS DR IMPLID. Ne AppIe deaIer,
agent, er empIeyee is autberized te make any
medificatien, extensien, er additien te tbis warranty.
Seme states de net aIIew tbe excIusien er Iimitatien
ef impIied warranties er IiabiIity fer incidentaI er
censequentiaI damages, se tbe abeve Iimitatien er
excIusien may net appIy te yeu. 7bis warranty gives
yeu specific IegaI rigbts, and yeu may aIse bave etber
rigbts wbicb vary frem state te state.