2011-05-26 53 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:

該方法直接從層樹呈現,忽略添加到呈現樹任何動畫。渲染圖層的座標空間。