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).
Contents Image
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];
Warning
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 setNeedsDisplay
(or 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 ...
Get Programming iOS 4 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.