실제로 CGContextRef 객체는 drawRect 메소드에서 설정된 후에 재사용 할 수 있습니다. 요점은 어디에서나 사용하기 전에 컨텍스트를 스택으로 푸시해야한다는 것입니다. 보기가 화면에 등장하기 전에 그렇지 않으면, 현재의 상황은 0x0으로
1. 당신의 @implementation에서
@interface RenderView : UIView {
CGContextRef visualContext;
BOOL renderFirst;
}
2. 추가 될 것입니다은 먼저, TRUE로 renderFirst을 설정
-(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가 그래픽 스택의 맨 위에서 자동으로 제거되는 것으로 보입니다.
어쨌든이 예제는 일종의 해킹 인 것 같습니다. Apple이 계획하고 제안한 것은 아닙니다. 이 솔루션은 매우 불안정하며 화면 맨 위에있는 하나의 UIView 내부에서만 직접 메서드 메시지 호출로 작동합니다. "performselection"호출의 경우 컨텍스트는 결과를 화면에 렌더링하지 않습니다. 그래서 CALayer를 직접적인 그래픽 컨텍스트 사용 대신 화면 타겟 렌더링에 사용하는 것이 좋습니다.
희망이 있습니다.
예,이 질문에 이미 스택 오버플로가 여러 차례 응답되었습니다. – borrrden
아직 무엇이 원인인지는 확실치 않지만 다른 누군가의 PDF를 사용하여 이미지 클래스를 작성하고 수정했습니다. 또한 drawRect에없는 UIGraphicsGetCurrentContext를 사용하므로 잘 동작합니다. –
@borrrden 비슷한 질문에 대한 링크를 제공해 주시겠습니까? – allenlinli