Drawing in a Layer

There are various ways to make a layer display something (apart from having a partnered view draw into it, as discussed in Chapter 15).

The simplest way to make something appear in a layer is through its contents property. This is parallel to the image in a UIImageView (Chapter 15). It is expected to be a CGImageRef (or nil, signifying no image). 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 as you assign it, like this:

layer.contents = (id)[im CGImage];

You may be wondering why, under ARC, we don’t also have to “cross the bridge” from the CFTypeRef world of a CGImageRef to the object world of an id by supplying a __bridge cast, as discussed in Chapter 12. It’s because the CGImage method is a Cocoa method and supplies ARC with the memory management information it needs. Coming back the other way, though, we would need an explicit __bridge cast:

CGImageRef imref = (__bridge CGImageRef)layer.contents;

Warning

Setting a layer’s contents to a UIImage, rather than a CGImage, will fail silently — the image doesn’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.

There are also four methods that can be implemented to provide or draw a layer’s content on demand, similar to a UIView’s drawRect:. A layer is very conservative about ...

Get Programming iOS 6, 3rd Edition 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.