将CALayer绘制到CGContext中

8

I have the following code:

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSaveGState(context);

CALayer *sublayer = [CALayer layer];
sublayer.backgroundColor = [UIColor orangeColor].CGColor;
sublayer.cornerRadius = 20.0;
sublayer.frame = CGRectMake(20, 0, 300, 20);

[sublayer setNeedsDisplay];
[sublayer drawInContext:context];

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return newImage;

但是当我查看返回的新图像时,只有一个空图像。当我将drawInContext更改为renderInContext时,我得到了上面的子层,但似乎坐标系混乱了。
有任何想法为什么上述的drawInContext没有起作用?
2个回答

11
尝试使用renderInContext代替drawInContext
我的理解是drawInContext可以被覆盖,而renderInContext用于将层的内容呈现到上下文中。
文档中可以看出: - drawInContext:

此方法的默认实现本身不进行任何绘制。如果层的委托实现了drawLayer:inContext:方法,则会调用该方法执行实际绘制。

子类可以重写此方法并使用它来绘制图层的内容。绘画时,所有坐标应在逻辑坐标空间中以点为单位指定。


- renderInContext:

此方法直接从图层树中呈现,忽略添加到渲染树中的任何动画。以图层的坐标空间呈现。


你很棒。 - Jatin Patel - JP
如果您的 backgroundColor、borderColor 或其他属性无法正常工作,这就是解决方案。您应该获得一张彩票。 - iOS Blacksmith

3

坐标系统本身并没有错乱。Quartz使用与UIKit不同的坐标系统。在Quartz中,Y轴起点位于框架矩形的左下角。随着沿着矩形向上移动,值变得越来越大。有关视觉表示,请参见文档:

http://developer.apple.com/library/mac/#documentation/graphicsimaging/Conceptual/drawingwithquartz2d/dq_overview/dq_overview.html

这与UIKit不同,因为UIKit的坐标系统原点是左上角,而随着向下移动,y轴值变得更正。

至于为什么drawInContext:不起作用,您还应该参考CALayer类的文档,其中写道:"默认实现什么也不做。"

http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CALayer_class/Introduction/Introduction.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接