iPhone Development – Adding an Image to a Layer

In order to do layer-based animation, you must add use a CALayer instance that holds the contents that you wish to animate. In this case I want an image (google logo) to be placed on the layer.

Here are the steps:

1. Create a new project that is a “View-Based Application”.

2. Add the “QuartzCore Framework and the CoreAnimation Framework” to your application (right click on the “frameworks folder” and click Add and then “Existing Frameworks”

3. Edit your ViewController header file and add “#import <QuartzCore/QuartzCore.h>”.

4. I’ll use a URL and place it in a UIImage instance. (google logo)

NSURL *url =
[NSURL URLWithString:@"http://www.google.com/intl/en_ALL/images/logo.gif"];
UIImage *displayImage =
[[UIImage alloc] initWithData:[self getImageData:url]];

2. Create a new layer (I am using a ViewController which is the owner (self).

CALayer *layer;
self.layer = [CALayer layer];

4. Create a CGRect to fix the display frame.

layer.frame = CGRectMake(18.0f, 150.0f, 276.0f, 110.0f);

5. Place the UIImage onto the layer. Note: You have to use the “CGImage” method to return a CGImage rather than a UIImage. Otherwise it won’t work. Casting is also required (id)

self.layer.contents = (id)[displayImage CGImage];

6. Add this new layer as a Sublayer to the current ViewControllers ‘view’ layer.

[self.view.layer addSublayer:self.layer];

7. Since we allocated the UIImage we need to release it.

[displayImage release];

Attached source…
SimpleLayer XCode Project

Bookmark and Share

Popularity: 54% [?]

Leave a comment

Your comment