I have been trying to us CALayers as "sprites" in an iPhone application I'm working on. From what I have been reading, that seems like the correct thing to do here.
When I setup the layer inside a UIView class I am able to get the layer to show up on the screen: NSLog(@"GameView initWithCoder");
NSString* imagePath = [[NSBundle mainBundle] pathForResource:@"earth" ofType:@"png"];
earthImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
earthLayer = [CALayer layer];
[earthLayer setContents:(id)[earthImage CGImage]];
[earthLayer setBounds:CGRectMake(0, 0, 32, 32)];
[earthLayer setPosition:CGPointMake(50, 50)];
[earthLayer setName:@"earth"];
[[self layer] addSublayer:earthLayer];
However, when I attempt to initialize the CALayer outside the UIView, my application crashes:
- (void)loadImage:(NSString*)fileName
{
NSLog(@"GamePiece loadImage");
NSArray* fileNameParts = [fileName componentsSeparatedByString:@"."];
imageName = [[fileNameParts objectAtIndex:0] retain];
NSString* ext = [fileNameParts objectAtIndex:1];
NSString* imagePath = [[NSBundle mainBundle] pathForResource:imageName ofType:ext];
image = [[UIImage alloc] initWithContentsOfFile:imagePath];
layer = [CALayer layer];
[layer setContents:(id)[image CGImage]];
[layer setBounds:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
[layer setPosition:CGPointMake(50.0f, 50.0f)];
[layer setName:imageName];
[fileNameParts release], fileNameParts = nil;
[ext release], ext = nil;
}
NSLog(@"GameView initWithCoder");
earth = [[GamePiece alloc] init];
[earth loadImage:@"earth.png"];
[[self layer] addSublayer:[earth layer]];
Clearly I'm doing something wrong here, but I just don't know what that would be. I have read the Core Animation Programming Guide and also the iPhone Application Programming Guide, but they really don't seem to talk about how to initialize a CALayer other than in passing.
I just need a gentle nudge in the correct direction. I have been getting a pretty good understanding about everything else I have learned when it comes to programming the iPhone. I'm just having some issues with Graphics, Layers and Animation.
Thanks in advance!