我一直在尝试将我们的 CALayers 作为我正在开发的 iPhone 应用程序中的“精灵”。从我一直在阅读的内容来看,这似乎是正确的做法。
当我在 UIView 类中设置图层时,我可以让图层显示在屏幕上: 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];
但是,当我尝试在 UIView 之外初始化 CALayer 时,我的应用程序崩溃了:
- (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]];
显然我在这里做错了什么,但我只是不知道那会是什么。我已经阅读了核心动画编程指南和 iPhone 应用程序编程指南,但他们似乎真的没有谈论如何初始化 CALayer,而不是顺便说一句。
我只需要在正确的方向轻轻推动。在 iPhone 编程方面,我对所学的所有其他知识都有了很好的理解。我只是在图形、图层和动画方面遇到了一些问题。
提前致谢!