Core Animation Isn't Just for Animation

- ( void ) createLayer

{

CGColorRef bgColor = CGColorCreateGenericGray ( 0.0 , 0.25 );



CALayer * myLayer = [ CALayer layer ] ;

myLayer .bounds = CGRectMake ( 0 , 0 , 150 , 150 );

myLayer .position = CGPointMake ( 20 , 20 );

myLayer .backgroundColor = bgColor;

myLayer .borderWidth = 1.5 ;



[parentLayer addSublayer : myLayer ] ;

CGColorRelease ( bgColor);

}

CAConstraintLayoutManager

Core Animation Isn't Just for Animation

Posted Oct 2, 2008 — 48 comments below Posted Oct 2, 2008 — 48 comments below

Often when I'm talking to somebody about how they're designing their app, I suggest they use Core Animation to implement the user interface. More times than I can count, I've gotten a puzzled look followed by the now-familiar "" response.Animation is the most significantthat Core Animation tackles, but it's far from being the only benefit. This is a really versatile framework with huge performance potential. You can have thousands of CALayers on the screen at the same time without breaking a sweat. It probably wouldn't be practical to try the same with NSView instances.There's a lot of GPU magic at play here. One element of it is the raw parallel processing power of modern graphics cards, and another is the fact that Core Animation can cache the contents of a CALayer on the card so that your code doesn't need to constantly redraw it. This, by the way, is part of the reason the iPhone UI is so incredibly fast on some relatively modest hardware. Core Animation can automatically take advantage of a multi-core Mac because the layer tree is rendered on a separate thread.The framework also provides a vastly simplified graphics model. Instead of requiring a view to implement all of the logic to manage abstract "layer-like" objects that are composited onto the screen, Core Animation provides actual on-screen layers that do all of the basics for you. Creating a layer is as simple as:Once a layer is created, it's easy to customize its appearance and behavior with delegate callbacks. The delegate can draw a layer's contents or can trigger actions — such as animations — in response to events. CALayers can also accept values for arbitrary keys using standard key-value coding methods. All of this means a greatly-reduced need for custom CALayer subclasses.Layout can either be done using NSView-like springs and struts, or by using the more sophisticatedclass, which sizes and positions layers relative to one-another based on per-layer rule sets.Of course you also get all of the well-publicized features of Core Animation: easy-to-use animations, 3D space, filters and transitions, shadows, per-layer transforms, and so on, but don't underestimate the advantages of it in more casual settings.