将CALayer绘制成CGContext

时间:2011-05-26 04:00:01

标签: calayer cgcontext

我有以下代码:

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;

但是当我查看返回的newImage时,只有一个空图像。当我将drawInContext更改为renderInContext时,我得到了上面的子图层,但看起来坐标系很糟糕。

任何想法为什么上面的drawInContext不起作用?

2 个答案:

答案 0 :(得分:7)

尝试使用renderInContext代替drawInContext

我的理解是drawInContext被覆盖,而renderInContext用于将图层的内容呈现给上下文。

来自the documentation

  

<强> - drawInContext:

     

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

     

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


  

<强> - renderInContext:

     

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

答案 1 :(得分: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