본문 바로가기

개발 Note/UI Framework 개발하기

CoreAnimation in iOS

반응형

에플 개발 사이트에서 core animation 관련 내용을 발최 필요한 부분을 번역하였습니다.


What Is Core Animation?

Core Animation is a collection of Objective-C classes for graphics rendering, projection, and animation. It 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:

- High performance compositing with a simple approachable programming model.
- A familiar view-like abstraction that allows you to create complex user interfaces using a hierarchy of layer objects.
- A lightweight data structure. You 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.
- Improved 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 APIs such as OpenGL to get respectable animation performance.


Core Animation Classes 


Core Animation classes can be grouped into several categories:
  • Layer classes that provide content for display

  • Animation and timing classes

  • Layout and constraint classes

  • A transaction class that groups multiple layer changes into an atomic update

기본 Core Animation class들은 Quartz Core framework.에 포함되어있고, 추가적인 layer class들은 다른 framework에 포함될 수 있다.  Figure 1 " Core Animation Class" class 계층도를 이다.

Figure 1 Core Animation class hierarchy
 



Layer Classes

Layer class는 Core Animation의 기반이며 NSView나 UIView를 이용하는 개발자들에게 친숙한 추상화(abstraction)를 제공한다. - abstraction 을 class 추상화 로 생각하는 것이 좋을것 같음.
CALayer는 모든 Core Animaton layer들의 부모 클래스로서 기본 Layer의 기능을 제공한다.
 

View 클래스의 인스턴스(객체) 는  레이어 트리에서 제공하는 것처럼 레이어 계층구조를 만든다.

 - CALayer 인스턴스는 하나의 부모 레이어(Super layer)와 자식 레이어(Sub Layer)들에 대한 콜랙션(collection- 자료구조)을 갖고 있다. 

레이어들은 뷰(View)와 비슷하게 뒤에서부터 앞으로 그려지고 부모 레이어(Super Layer)를 로컬(local) 좌표계를 생성하는 것과 같이 상대적 위치나 형태를 취하게 된다. 
그러나, 레이어들은  회전(rotate),비틀림(skew), 크기변환( scale) , 투영(project)와 같은 변환 행렬을 레이어 컨텐츠(content)에 적용하는 것과 같은 좀더 복잡한 표현들을 제공한다. 

"Layer Geometry and Transforms" 는 레이어 도형(Geometry) 와 변환(transform)에 대해 좀더 자세하게 다루고 있다.

 CALayer는 Application Kit과 Cocoa Touch view class들로 분기하기에, 컨텐츠를 표현하기 위해 CALayer에서 파생(subclass)될 필요가 없다. 컨텐츠는 CALayer 인스턴스에 의해 아래와 같은 방법으로 출력된다.

  • Core Graphics 의 Image Representation 으로 직접 또는 델리게이션(delegation)을 통해서 레이어의 컨텐츠 속성(property) 세팅.
  • Core Graphics Image Context를 통해 직접 그리는 델리게이트( delegate)를 제공.
  • 여러가지 비쥬얼 스타일 속성 설정 제공
    • 모든레이어에 공통적으로 가지고 있는 속성으로 예를 들면,
    • 배경색( background color), 투명도(opacity), 마스킹(masking)등이다. 
      - Mac OS X 어플리케이션 역시 비쥬얼 속성( property)을 접근할 수 있으며 Core Image filter를 사용할수 있다.
  • CALayer 파생(상속, subclassing) 이나 좀더 켑슐화된 방법의 높은 수준의 기술을 통한 구현.



“Providing Layer Content” 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.”

In addition to the CALayer class, the Core Animation class collection provides additional classes that allow applications to display other types of content. The available classes differ slightly between Mac OS X and iOS. The following classes are available on both Mac OS X and iOS:

  • CAScrollLayer class is a subclass of CALayer that simplifies displaying a portion of a layer. The extent of the scrollable area of a CAScrollLayer object is defined by the layout of its sublayers. CAScrollLayer does not provide keyboard or mouse event-handling, nor does it provide visible scrollers.

  • CATextLayer is a convenience class that creates a layer's content from a string or attributed string.

  • CATiledLayer allows the display of large and complex images in incremental stages.

Mac OS X provides these additional classes:

  • CAOpenGLLayer provides an OpenGL rendering environment. You must subclass this class to provide content using OpenGL. The content can be static or can be updated over time.

  • QCCompositionLayer (provided by the Quartz Composer framework) animates a Quartz Composer composition as its content.

  • QTMovieLayer and QTCaptureLayer (provided by the QTKit framework) provides playback of QuickTime movies and live video.

iOS adds the following class:

  • CAEAGLLayer provides an OpenGLES rendering environment.

The CALayer class introduces the concept of a key-value coding compliant container class–that is, a class that can store arbitrary values, using key-value coding compliant methods, without having to create a subclass. CALayer also extends the NSKeyValueCoding informal protocol, adding support for default key values and automatic object wrapping for the additional structure types (CGPointCGSizeCGRectCGAffineTransform and CATransform3D) and provides access to many of the fields of those structures by key path.

CALayer also manages the animations and actions that are associated with a layer. Layers receive action triggers in response to layers being inserted and removed from the layer tree, modifications being made to layer properties, or explicit developer requests. These actions typically result in an animation occurring. See “Animation” and “Layer Actions” for more information.

Animation and Timing Classes


한 레이어의 비쥬얼 프라퍼티들중 많은 것들이 Implicitly(자동,무조건적인) 에니메이션 가능하다. 에니메이션이 가능한 프라퍼티의 값을 간단히 변경하는 것으로 레이어는 자동으로 현재 값에서 새로 세팅된 값으로 에니메이션 한다. 예로 레이어의 숨김(hidden) 프라퍼티를 YES로 설정하면 레이어는 천천히 사라진다. 대부분의 에니메이션이 가능한 프라퍼티들은 사용자가 조작하거나 변경할수 있도록 기본적인 에니메이션을 가지고 있다. 에니메이션 가능한 프라퍼티의 전체 목록은 "Animatable Properties" 에 있다.



에니메이션 프라퍼티들은 explicit 에니메이션으로 사용할 수 있다. Core Animation 의 animation class 로 인스턴스를 만들고 비쥬얼 이펙트를 설정하여 explicit 에니메이션을 만들 수 있다.
explicit animation은 Layer에서 프라퍼티 값을 변경하지 않고, display 단에서 간단한 에니메이션을 한다. 
(
An explicit animation doesn’t change the value of the property in the layer, it simply animates it in the display.


제가 알아본 결과 : 
explicit animation 은 layer에 사용자가 원하는 에니메이션을 세팅 할 수 있는 기능으로,animation 되는 동안 layer의 property는 변경되지 않는 다고 합니다.
 

 


Core Animation provides animation classes that can animate the entire contents of a layer or selected attributes using both basic animation and key-frame animation. All Core Animation's animation classes descend from the abstract class 
CAAnimationCAAnimation adopts the CAMediaTiming protocol which provides the simple duration, speed, and repeat count for an animation.CAAnimation also adopts the CAAction protocol. This protocol provides a standardized means for starting an animation in response to an action triggered by a layer.

The animation classes also define a timing function that describes the pacing of the animation as a simple Bezier curve. For example, a linear timing function specifies that the animation's pace is even across its duration, while an ease-out timing function causes an animation to slow down as it nears its duration.

Core Animation provides a number of additional abstract and concrete animation classes:

  • CATransition provides a transition effect that affects the entire layer's content. It fades, pushes, or reveals layer content when animating. The stock transition effects can be extended by providing your own custom Core Image filters.

  • CAAnimationGroup allows an array of animation objects to be grouped together and run concurrently.

  • CAPropertyAnimation is an abstract subclass that provides support for animating a layer property specified by a key path.

  • CABasicAnimation provides simple interpolation for a layer property.

  • CAKeyframeAnimation provides support for key frame animation. You 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” describes the classes as they pertain to Core Animation, Animation Types and Timing Programming Guide 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 Mac OS X also provides a more flexible layout manager mechanism that allows developers to write their own layout managers.

Core Animation’s CAConstraint class is a layout manager that arranges sublayers using a set of constraints that you specify. Each constraint (encapsulated by instances of the CAConstraintclass) describes the relationship of one geometric attribute of a layer (the left, right, top, or bottom edge 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”

Transaction Management Classes

Every modification to an animatable property of a layer must be part of a transaction. CATransaction is the Core Animation class responsible for batching multiple animation operations into atomic updates to the display. Nested transactions are supported.


Core Animation 은 implicit transaction 와 explicit transaction  2가지 타입의 트랜젝션(transaction)을 제공한다. 
Implicit transaction은 쓰레드(thread)에서 active transaction 없이 레이어의 에니메이션가능한 속성이 수정되면 자동으로 생성된다.  그리고 쓰레드 루프(run-loop)에서 다음 수행(iterate)될때 자동으로 수행된다. 
Explicit transaction 은 어플리케이션이 레이어를 수정하기 전에 CATransaction class의 begin message 를 보내고  commit message를 할때 수행된다. 

 

Transaction management is discussed in “Transactions.”




Core Animation Rendering Architecture

Core Animation의 Layer와 Cocoa view사이에 명백하게 비슷한 점들이 있는 동시에 가장 큰 념적인 차이는 스크린에 직접 그리지는 않는다.

NSView와 UIView는 MVC(model-view-controller)디자인 패턴에서 뷰 오브젝트(view object)에 해당하고, Core Animation 의 Layer는 모델 오브젝트(model object)에 해당한다. Layer는 형체 정보(geometry), 타이밍(timing) 과 visual property, 그들이 제공하는 표시된 컨텐츠(content)를 켑슐화(encapsulate)하고 있으나, 실제 보여지는 것이 Layer의  기능은 아니다.


각의 레이어 트리에는 2개의 대응되는 트리가 있다. Presentation tree와 Render Tree이다.
그림1은 Mac OS X에서의 유효한 Core Animation layer class를 이용한 Layer트리의 예를 보여준다.
 

Figure 1  Core Animation Rendering Architecture



레이어 트리(Layer tree)는 각 레이어의 객체 모델 값(Value)들을 포함하고 있다. 이 값들은 레이어 프라퍼티(Layer property)에 설정한 값이다.

Presentation Tree 는 현재 에니메이션 위치의 값들을 가지고있다.
한 예로 새로운 값을 Layer의 backgroundColor에 설정하면, Layer tree의 값은 즉시 바뀐다. 그러나 Presentation tree에 해당하는 Layer의 backgroundColor 값은 presentation tree의 layer들이 화면에 반영되는 시점에 업데이트된다.
(interpolate 되는 시점이 rendering 직전이라고 이해하면 될것 같다).

레이어를 렌더링 할때 렌더 트리는 presentation-tree의 값을 사용한다. 렌더 트리는 어플리케이션의 엑티비티와는 독립적으로 구성가능하도록 하는 역할을 맡고있다.
렌더링이 어플리케이션 실행 루프에서 최소한의 영향을 주도록 분리된 프로세스나 스레드에서 실행된다.

프로세스내에서 animation이 수행되는 동안 Presentation Layer에 해당하는 CALayer의 인스턴스에 접근할 수 있다.
이는 현재 에니매이션되고 있는 상태를 가지고 새로운 에니메이션을 시키고자할때 매우 유용하다. 






Layer Geometry and Transforms

This chapter describes the components of a layer’s geometry, how they interrelate, and how transform matrices can produce complex visual effects.

Layer Coordinate System

The coordinate system for layers differs depending on the current platform. In 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. In Mac 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 platform use the default coordinate system associated with that platform.

Every layer object 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. Because each layer defines its own coordinate system, the CALayer 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. (For 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 Geometry

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.

Figure 1 shows the properties used to specify a layer's geometry in context.

Figure 1  CALayer geometry properties


The position property is a CGPoint that specifies the position of the layer relative to its superlayer, and is expressed in the superlayer's coordinate system.

The bounds property is a CGRect that provides the size of the layer (bounds.size) and the origin (bounds.origin). The bounds origin is used as the origin of the graphics context when you override a layer's drawing methods.

Layers have an implicit frame that is a function of the positionboundsanchorPoint, and transform properties. Setting a new frame rectangle changes the layer's position and boundsproperties 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 frame property value, it is calculated relative to the positionbounds, and anchorPoint properties.

The anchorPoint property is a CGPoint that specifies a location within the bounds of a layer that corresponds with the position coordinate. The anchor point specifies how the bounds are positioned relative to the position property, as well as serving as the point that transforms are applied around. It 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 anchorPoint orientation, depending on the parent’s coordinate system on the y-axis.

When you specify the frame of a layer, position is set relative to the anchor point. When you specify the position of the layer, bounds is set relative to the anchor point.

Figure 2 shows three example values for an anchor point.

Figure 2  Three anchorPoint values


The default value for anchorPoint is (0.5,0.5) which corresponds to the center of the layer's bounds (shown as point A in Figure 2.) Point B shows the position of an anchor point set to (0.0,0.5). Finally, point C (1.0,0.0) causes specifies that the layer’s position is set to the bottom right corner of the frame. This diagram is specific to layers in Mac OS X. In 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.

The relationship of the frameboundsposition, and anchorPoint properties is shown in Figure 3.

Figure 3  Layer Origin of (0.5,0.5)


In this example the anchorPoint is set to the default value of (0.5,0.5), which corresponds to the center of the layer. The position of the layer is set to (100.0,100.0), and the bounds 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).

If you created a new layer, and set only the layer’s frame property to (40.0, 60.0, 120.0, 80.0), the position property would be automatically set to (100.0,100.0), and the bounds property to (0.0, 0.0, 120.0, 80.0).

Figure 4 shows a layer with the same frame rectangle as the layer in Figure 3. However, in this case the anchorPoint of the layer is set to (0.0,0.0), which corresponds with the bottom left corner of the layer.

Figure 4  Layer Origin of (0.0,0.0)


With the frame set to (40.0, 60.0, 120.0, 80.0), the value of the bounds property is the same, but the value of the position property has changed.

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 cornerRadius property specifies a radius the layer uses when drawing content, clipping sublayers, and drawing the border and shadow.

The zPosition property specifies the z-axis component of the layer's position. The zPosition is intended to be used to set the visual position of the layer relative to its sibling layers. It should not be used to specify the order of layer siblings, instead reorder the layer in the sublayer array.

Transforming a Layer’s Geometry

Once established, you can transform a layer's geometry using matrix transformations. The CATransform3D data structure defines a homogenous three-dimensional transform (a 4 by 4 matrix ofCGFloat values) that is used to rotate, scale, offset, skew, and apply perspective transformations to a layer.

Two layer properties specify transform matrices: transform and sublayerTransform. The matrix specified by the transform property is applied to the layer and its sublayers relative to the layer's anchorPointFigure 3 shows how rotation and scaling transforms affect a layer when using an anchorPoint of (0.5,0.5), the default value. Figure 4 shows how the same transform matrices affect a layer when an anchorPoint of (0.0,0.0). The matrix specified by the sublayerTransform property is applied only to the layer’s sublayers, rather than to the layer itself.

You create and modify CATransform3D data structures in one of the following ways:

  • using the CATransform3D functions

  • modifying the data structure members directly

  • using key-value coding and key paths.

The constant CATransform3DIdentity is the identity matrix, a matrix that has no scale, rotation, skewing, or perspective applied. Applying the identity matrix to a layer causes it to be displayed with its default geometry.

Transform Functions

The transform functions available in Core Animation operate on matrices. You can use these functions (shown in Table 1) to construct a matrix that you later apply to a layer or its sublayers by modifying the transform or sublayerTransform properties respectively. The transform functions either operate on, or return, a CATransform3D data structure. This enables you to construct simple or complex transforms that you can readily reuse.

Table 1  CATransform3D transform functions for translation, rotation, and scaling

Function

Use

CATransform3DMakeTranslation

Returns a transform that translates by '(tx, ty, tz)'. t' = [1 0 0 0; 0 1 0 0; 0 0 1 0; tx ty tz 1].

CATransform3DTranslate

Translate 't' by '(tx, ty, tz)' and return the result: * t' = translate(tx, ty, tz) * t.

CATransform3DMakeScale

Returns a transform that scales by `(sx, sy, sz)': * t' = [sx 0 0 0; 0 sy 0 0; 0 0 sz 0; 0 0 0 1].

CATransform3DScale

Scale 't' by '(sx, sy, sz)' and return the result: * t' = scale(sx, sy, sz) * t.

CATransform3DMakeRotation

Returns a transform that rotates by 'angle' radians about the vector '(x, y, z)'. If the vector has length zero the identity transform is returned.

CATransform3DRotate

Rotate 't' by 'angle' radians about the vector '(x, y, z)' and return the result. t' = rotation(angle, x, y, z) * t.

The angle of rotation is specified in radians rather than degrees. The following functions allow you to convert between radians and degrees.

CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
CGFloat RadiansToDegrees(CGFloat radians) {return radians * 180 / M_PI;};

Core Animation provides a transform function that inverts a matrix, CATransform3DInvert. Inversion is generally used to provide reverse transformation of points within transformed objects. Inversion can be useful when you need to recover a value that has been transformed by a matrix: invert the matrix, and multiply the value by the inverted matrix, and the result is the original value.

Functions are also provided that allow you to convert a CATransform3D matrix to a CGAffineTransform matrix, if the CATransform3D matrix can be expressed as such.

Table 2  CATransform3D transform functions for CGAffineTransform conversion

Function

Use

CATransform3DMakeAffineTransform

Returns a CATransform3D with the same effect as the passed affine transform.

CATransform3DIsAffine

Returns YES if the passed CATransform3D can be exactly represented an affine transform.

CATransform3DGetAffineTransform

Returns the affine transform represented by the passed CATransform3D.

Functions are provided for comparing transform matrices for equality with the identity matrix, or another transform matrix.

Table 3  CATransform3D transform functions for testing equality

Function

Use

CATransform3DIsIdentity

Returns YES if the transform is the identity transform.

CATransform3DEqualToTransform

Returns YES if the two transforms are exactly equal..

Modifying the Transform Data Structure

You can modify the value of any of the CATransform3D data structure members as you would any other data structure. Listing 1 contains the definition of the CATransform3D data structure, the structure members are shown in their corresponding matrix positions.

Listing 1  CATransform3D structure

struct CATransform3D

{


  CGFloat m11, m12, m13, m14;

  CGFloat m21, m22, m23, m24;

  CGFloat m31, m32, m33, m34;

  CGFloat m41, m42, m43, m44;

};

 

typedef struct CATransform3D CATransform3D;




 

The example in Listing 2 illustrates how to configure a CATransform3D as a perspective transform.

Listing 2  Modifying the CATransform3D data structure directly

 CATransform3D aTransform = CATransform3DIdentity;

// the value of zDistance affects the sharpness of the transform.

zDistance = 850;

aTransform.m34 = 1.0 / -zDistance;




Modifying a Transform Using Key Paths

Core Animation extends the key-value coding protocol to allow getting and setting of the common values of a layer's CATransform3D matrix through key paths. Table 4 describes the key paths for which a layer’s transform and sublayerTransform properties are key-value coding and observing compliant.

Table 4  CATransform3D key paths

Field Key Path

Description

rotation.x

The rotation, in radians, in the x axis.

rotation.y

The rotation, in radians, in the y axis.

rotation.z

The rotation, in radians, in the z axis.

rotation

The rotation, in radians, in the z axis. This is identical to setting the rotation.z field.

scale.x

Scale factor for the x axis.

scale.y

Scale factor for the y axis.

scale.z

Scale factor for the z axis.

scale

Average of all three scale factors.

translation.x

Translate in the x axis.

translation.y

Translate in the y axis.

translation.z

Translate in the z axis.

translation

Translate in the x and y axis. Value is an NSSize or CGSize.

You can not specify a structure field key path using Objective-C 2.0 properties. This will not work:

myLayer.transform.rotation.x=0;

Instead you must use setValue:forKeyPath: or valueForKeyPath: as shown below:

[myLayer setValue:[NSNumber numberWithInt:0] forKeyPath:@"transform.rotation.x"]




 [펌]http://developer.apple.com