2011-05-26 54 views
5

我有以下代码:画的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不起作用?

回答

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

2

尝试代替drawInContext使用renderInContext

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

the documentation

- drawInContext:

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

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


- renderInContext:

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