简体   繁体   English

为什么此CALayer不显示图像?

[英]Why does this CALayer not display an image?

Can you guys tell why this code shows no image? 你们能说出为什么这段代码没有显示图像吗?

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];

This Quartz stuff is driving me crazy! 这些石英材料使我发疯! Please help! 请帮忙!

Yes, the image is there and is working, but all I see after this code is a blank screen. 是的,图像在那里并且正在工作,但是在这段代码之后我看到的只是一个空白屏幕。

I assume that this code is from your view controller and that its view has been properly constructed before this (otherwise, you'll be sending messages to nil). 我假设这段代码来自您的视图控制器,并且在此之前它的视图已经正确构建(否则,您将向nil发送消息)。 Also, I assume by addedObject above, you mean selectedImage . 另外,我假设上面的addedObject是指selectedImage One thing that jumps out at me is that 让我惊讶的一件事是

[layerBack display];

should be replaced with 应该替换为

[layerBack setNeedsDisplay];

From the CALayer documentation , in regards to -display: CALayer文档中 ,关于-display:

You should not call this method directly. 您不应该直接调用此方法。

There's more on setting the content of layers like this in the "Providing Layer Content" section of the Core Animation Programming Guide. 核心动画编程指南“提供图层内容”部分提供了更多有关设置图层内容的信息

Well first of all I think you have to cast the CGImage to an id. 好吧,首先,我认为您必须将CGImage转换为id。

layerBack.contents = (id)selectedImage.CGImage;

And secondly, I think you have to add the layer to the views content layer 其次,我认为您必须将该层添加到视图内容层

[self.view.layer addSublayer:layerBack];

But I have always made use of my custom UIViews class's + (Class)layerClass; 但是我一直使用自定义UIViews类的+(Class)layerClass; to generate custom layers which layout their own sublayers, but maybe that's just me. 来生成自定义图层,以布局自己的子图层,但这也许就是我。

What is selectedImage and how does it relate to addedObject? 什么是selectedImage,它与addedObject有什么关系? From what I see, you get an image, but then add in an entirely different, unrelated image, possibly a blank one, to the layer. 据我所知,您获得了一张图像,但是将一个完全不同的,不相关的图像(可能是空白图像)添加到了图层中。

Are you paying attention to messages Xcode is providing you? 您是否在关注Xcode向您提供的消息?

桥接它:

layerBack.contents = (__bridge id)selectedImage.CGImage;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM