[英]Drawing a UIImage into CALayer.contents does not render image data
I am having a wicked time trying to get an image to show up in a CALayer.contents
. 我有一个邪恶的时间试图让图像显示在
CALayer.contents
。 It seems rather straight forward but I cannot get the image to render no matter what I do. 它似乎相当直接,但无论我做什么,我都无法渲染图像。 The
CALayer
renders fine as I can see its background color and corner radius, but the image will not load. CALayer
渲染得很好,因为我可以看到它的背景颜色和角半径,但图像不会加载。
What you are seeing here is a CAGradientLayer
subclass with a mask applied. 你在这里看到的是一个应用了蒙版的
CAGradientLayer
子类。 The inner square is where I would like the image to show, and it is added as a sublayer of the CAGradientLayer
subclass. 内部正方形是我希望图像显示的位置,并且它被添加为
CAGradientLayer
子类的子图层。
The code to set this up is pretty straightforward. 设置它的代码非常简单。 In
init
: 在
init
:
self.imageLayer = [CALayer layer];
self.imageLayer.cornerRadius = kDefaultCornerRadius;
self.imageLayer.backgroundColor = [UIColor darkGrayColor].CGColor;
[self addSublayer:self.imageLayer];
Then later on, I set the image: 然后,我设置图像:
- (void)setImage:(UIImage *)image {
self.imageLayer.contents = (id)image.CGImage;
[self.imageLayer setNeedsDisplay];
}
Finally, within setFrame
: 最后,在
setFrame
:
CGFloat imageSize = self.bounds.size.width - 2*kDefaultMargin;
[self.imageLayer setBounds:CGRectMake(0.0, 0.0, imageSize, imageSize)];
[self.imageLayer setPosition:CGPointMake(self.bounds.size.width/2.0f, kDefaultMargin + imageSize/2.0f)];
[self.imageLayer setNeedsDisplay];
Things I already know or have checked: 我已经知道或检查过的事情:
[UIImage imageNamed:@"info.png"]
is being used elsewhere in the code and actually shows and image. [UIImage imageNamed:@"info.png"]
正在代码中的其他地方使用,实际上是显示和图像。 It is 16x16 at 1x and 32x32 at 2x init
, setImage:
, setFrame
; init
, setImage:
, setFrame
; What is going on here? 这里发生了什么?
Remove this line: 删除此行:
[self.imageLayer setNeedsDisplay];
-setNeedsDisplay
tells a layer that it needs to redraw its contents. -setNeedsDisplay
告诉图层它需要重绘其内容。 Since you already provided the content for the layer, you don't want CA to discard that content and ask for a replacement. 由于您已经为图层提供了内容,因此您不希望CA放弃该内容并要求替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.