2012-09-14 78 views
12

我想在這裏將單個PDF頁面轉換爲PNG,並且直到UIGraphicsGetCurrentContext突然開始返回nil,它才能正常工作。UIGraphicsGetCurrentContext似乎返回零

我試圖在這裏追溯我的步驟,但我不太確定我知道發生了什麼。我的框架不是0,我認爲這可能會造成這個問題,但除此之外,一切「看起來」都是正確的。

這是我的代碼的開始。

_pdf = CGPDFDocumentCreateWithURL((__bridge CFURLRef)_pdfFileUrl); 
CGPDFPageRef myPageRef = CGPDFDocumentGetPage(_pdf, pageNumber); 
CGRect aRect = CGPDFPageGetBoxRect(myPageRef, kCGPDFCropBox); 
CGRect bRect = CGRectMake(0, 0, height/(aRect.size.height/aRect.size.width), height); 
UIGraphicsBeginImageContext(bRect.size); 
CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextSaveGState(context); 

任何人都有什麼想法可能會導致無上下文?

回答

2

事實上,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作爲屏幕目標的渲染,而不是直接的圖形上下文使用。
希望它有幫助。

28

您是否在drawRect方法內調用UIGraphicsGetCurrentContext()?據我所知,它只能在drawRect中調用,否則它只會返回nil。

+0

是的,這個問題已經在Stack Overflow已經被回答了好幾次了! – borrrden

+0

仍然不確定是什麼導致它,但我用別人的PDF在這裏圖像類,並修復它。也使用UIGraphicsGetCurrentContext而不在drawRect中,它在那裏工作正常。 –

+0

@borrrden你能給我一些類似問題的鏈接嗎? – allenlinli

34

它不必從「drawRect」中調用。 你也可以在「UIGraphicsBeginImageContext(bRect.size);」之後調用它。

入住下面一行

UIGraphicsBeginImageContext(bRect.size); 

如果bRect.size不是0,0

在我而言,這是爲什麼在下一行返回的情況下爲null。

+3

是的,我的問題是,大小是CGSizeZero – ninjaneer