为什么此CALayer不显示图像?

时间:2009-09-10 11:55:55

标签: iphone cocoa core-animation

你们能说出为什么这段代码没有显示图像吗?

CALayer *layerBack = [CALayer layer];

addedObject = [[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle] 
    pathForResource:[NSString stringWithFormat: @"%@%d", PREFIX, number] ofType:@"png"]];

layerBack.bounds=CGRectMake(0.0f,0.0f,selectedImage.size.height,selectedImage.size.width);
layerBack.position=CGPointMake(200,200);

layerBack.contents = (id)selectedImage.CGImage;
// in theory I think this line should be equal to selectedImage.CGImage, but when I do that, Xcode shows me an error!

[self.view.layer addSublayer:layerBack];

[layerBack display];

这个石英的东西让我抓狂!请帮忙!

是的,图像在那里并且正在工作,但我在此代码后看到的只是一个空白屏幕。

4 个答案:

答案 0 :(得分:3)

我假设此代码来自您的视图控制器,并且在此之前已正确构建其视图(否则,您将向nil发送消息)。另外,我假设上面的addedObject,您的意思是selectedImage。跳出来的一件事是

[layerBack display];

应替换为

[layerBack setNeedsDisplay];

关于-display:

,来自CALayer documentation
  

您不应该调用此方法   直接

在核心动画编程指南的"Providing Layer Content"部分中,有更多关于如此设置图层内容的内容。

答案 1 :(得分:2)

首先,我认为你必须将CGImage转换为id。

layerBack.contents = (id)selectedImage.CGImage;

其次,我认为你必须将图层添加到视图内容层

[self.view.layer addSublayer:layerBack];

但我总是使用我的自定义UIViews类的+(Class)layerClass;生成自定义图层,布局自己的子图层,但也许只是我。

答案 2 :(得分:1)

selectedImage是什么以及它与addedObject的关系?从我看到的,你得到一个图像,但然后添加一个完全不同的,不相关的图像,可能是一个空白的图像。

您是否关注Xcode为您提供的消息?

答案 3 :(得分:1)

桥接它:

layerBack.contents = (__bridge id)selectedImage.CGImage;
相关问题