When to use CALayer on the Mac/iPhone?

2019-01-13 06:41发布

问题:

I'm slightly confused when to use CALayer on the iPhone or Mac and when not to use it? CoreAnimation works just fine on my UIView based objects without having to use CALayer. When is the appropriate time to dig into this class?

回答1:

In my benchmarks, UIView and CALayer provide about the same level of performance on the iPhone. As rpetrich mentions in his comment, UIViews are a thin wrapper around CALayers. On the Mac, CALayers are much more lightweight than NSViews.

As Ben points out, you can go beyond the capabilities of implicit animations by working directly with CALayers, even providing some 3-D effects through CATransform3D. In many cases, you can do this even with your standard views by accessing the backing layer (if the view is layer-backed).

Another concern is cross-platform (Mac / iPhone) code. My iPhone application uses an all-CALayer interface for its primary view in large part because I can use the exact same code for drawing that interface in its Mac counterpart. For another example of this, I direct you to the Core Plot framework, which draws graphs entirely using CALayers and works on both Mac and iPhone. CALayers are pretty much the same on both platforms, where UIView and NSView have very different interfaces.



回答2:

If you can do what you want with 'implicit animation' (that offered by UIKit/AppKit without having to dig into CA,layers, and animators) then definitely go that route.

CoreAnimation comes into play when you start using more complex animations, such as non-linear motion, or repeating effects, and certain synchronized effects. There's a LOT you can do with it, but it is a pretty heavy duty tool (with a commensurate learning curve, at least compared to the UIKit stuff).