事實上,CGContextRef對象可以在drawRect方法中設置後重用。 問題是 - 在從任何地方使用它之前,您需要將Context推入堆棧。否則,當前上下文將爲0x0
1.添加
@interface RenderView : UIView {
CGContextRef visualContext;
BOOL renderFirst;
}
2.在你的@implementation首先設置renderFirst爲TRUE觀點已經出現在屏幕上之前,則:
-(void) drawRect:(CGRect) rect {
if (renderFirst) {
visualContext = UIGraphicsGetCurrentContext();
renderFirst = FALSE;
}
}
3 。在設置上下文之後渲染一些東西。
-(void) renderSomethingToRect:(CGRect) rect {
UIGraphicsPushContext(visualContext);
// For instance
UIGraphicsPushContext(visualContext);
CGContextSetRGBFillColor(visualContext, 1.0, 1.0, 1.0, 1.0);
CGContextFillRect(visualContext, rect);
}
下面是一個例子完全線程情況下匹配:
- (void) drawImage: (CGImageRef) img inRect: (CGRect) aRect {
UIGraphicsBeginImageContextWithOptions(aRect.size, NO, 0.0);
visualContext = UIGraphicsGetCurrentContext();
CGContextConcatCTM(visualContext, CGAffineTransformMakeTranslation(-aRect.origin.x, -aRect.origin.y));
CGContextClipToRect(visualContext, aRect);
CGContextDrawImage(visualContext, aRect, img);
// this can be used for drawing image on CALayer
self.layer.contents = (__bridge id) img;
[CATransaction flush];
UIGraphicsEndImageContext();
}
和繪畫從上下文圖像這是在這個崗位之前拍攝:
-(void) drawImageOnContext: (CGImageRef) someIm onPosition: (CGPoint) aPos {
UIGraphicsPushContext(visualContext);
CGContextDrawImage(visualContext, CGRectMake(aPos.x,
aPos.y, someIm.size.width,
someIm.size.height), someIm.CGImage);
}
不要調用UIGraphicsPopContext()函數,直到需要上下文來呈現對象。
當調用方法結束時,似乎CGContextRef自動從圖形堆棧的頂部被移除。
無論如何,這個例子似乎是一種黑客 - 並非由蘋果計劃和提出。該解決方案非常不穩定,只能在屏幕頂部的一個UIView內直接調用方法消息。在「執行選擇」調用的情況下,上下文不會在屏幕上顯示任何結果。所以,我建議使用CALayer作爲屏幕目標的渲染,而不是直接的圖形上下文使用。
希望它有幫助。
是的,這個問題已經在Stack Overflow已經被回答了好幾次了! – borrrden
仍然不確定是什麼導致它,但我用別人的PDF在這裏圖像類,並修復它。也使用UIGraphicsGetCurrentContext而不在drawRect中,它在那裏工作正常。 –
@borrrden你能給我一些類似問題的鏈接嗎? – allenlinli