O'Reilly logo

Programming iOS 4 by Matt Neuburg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required