Drawing in a Layer
There are various ways to make a layer display something (apart from its
backgroundColor and having a partnered view draw into it).
A layer has a
contents property. This is parallel to the
image in a UIImageView (Chapter 15); indeed, it is expected to be a CGImageRef (or nil, signifying no contents). A CGImageRef is not an object type, but the
contents property is typed as an
id; in order to quiet the compiler, you’ll have to typecast your CGImageRef to an
id (or a
void*) as you assign it, like this:
arrow.contents = (id)[im CGImage];
Setting a layer’s
contents to a UIImage, rather than a CGImage, will fail silently — the contents don’t appear, but there is no error either. This is absolutely maddening, and I wish I had a nickel for every time I’ve done it and then wasted hours figuring out why my layer isn’t appearing.
Contents on Demand
There are four methods that can be implemented to provide or draw a layer’s contents on demand, similar to a UIView’s
drawRect:. A layer is very conservative about calling these methods (and you must not call any of them directly). If the layer’s
needsDisplayOnBoundsChange property is NO (the default), then the only way to cause these methods to be called is by calling
setNeedsDisplayInRect:). Even this might not cause these methods to be called right away; if that’s crucial, then you will also call
displayIfNeeded. If the layer’s
needsDisplayOnBoundsChange property is YES, then these methods ...