2010-08-06 104 views
4

我有我的CGImageRef,我想通過我的NSView顯示它。但是這段代碼似乎不起作用,我已經從源代碼路徑中獲得了CGImageRef。這裏是我的代碼:使用CGImage繪製圖像?

- (void)drawRect:(NSRect)rect { 

NSString * thePath = [[NSBundle mainBundle] pathForResource: @"blue_pict" 
                ofType: @"jpg"]; 
NSLog(@"the path : %@", thePath); 

CGImageRef myDrawnImage = [self createCGImageRefFromFile:thePath]; 

NSLog(@"get the context"); 
CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext]  graphicsPort]; 
if (context==nil) { 
    NSLog(@"context failed"); 
    return; 
} 

//get the bitmap context 
CGContextRef myContextRef = CreateARGBBitmapContext(myDrawnImage); 

//set the rectangle 
NSLog(@"get the size for imageRect"); 
size_t w = CGImageGetWidth(myDrawnImage); 
size_t h = CGImageGetHeight(myDrawnImage); 
CGRect imageRect = {{0,0}, {w,h}}; 
NSLog(@"W : %d", w); 

myDrawnImage = CGBitmapContextCreateImage(myContextRef); 

NSLog(@"now draw it"); 
CGContextDrawImage(context, imageRect, myDrawnImage); 

char *bitmapData = CGBitmapContextGetData(myContextRef); 

NSLog(@"and release it"); 
CGContextRelease(myContextRef); 
if (bitmapData) free(bitmapData); 
CGImageRelease(myDrawnImage); 

}

什麼不好的代碼?

  • 感謝&方面 -

回答

1

是,你實際上並沒有繪製圖像。您只需使用CGContextDrawImage而不是創建空位圖上下文。

+0

感謝您的快速回復。 因此,我應該將生成的CGImage更改爲NSImage以便將其繪製到NSView中?所以然後我可以使用通用繪製方法,如 [myNSImage drawInRect:fromRect:operation:fraction] – Hebbian 2010-08-06 14:16:54

+0

您可以這樣做,是的。除非你不需要圖像作爲Core Graphics圖像,否則我會建議你使用NSImage來完成你的任務。 – SteamTrout 2010-08-06 14:26:59

4
CGImageRef myDrawnImage = [self createCGImageRefFromFile:thePath]; 

現在,你有你的形象。

CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext]  graphicsPort]; 

現在,你有你的畫面的內容。您擁有繪製圖像所需的一切。

CGContextRef myContextRef = CreateARGBBitmapContext(myDrawnImage); 

等等,什麼?

myDrawnImage = CGBitmapContextCreateImage(myContextRef); 

的... ...凱現在你已經捕獲了什麼都沒有繪製在上下文的內容,忘記了(和泄漏)你用空白圖像替換它加載的圖像。

CGContextDrawImage(context, imageRect, myDrawnImage); 

你畫的空白圖像。

刪除位圖上下文的創建並創建該上下文內容的圖像,並將您加載的圖像繪製到視圖的上下文中。

或使用NSImage。這將是一個雙線。

+0

感謝Peter的回覆。 是的,myDrawnImage = CGBitmapContextCreateImage(myContextRef);只是用新的空白圖像替換我的位圖(我的壞)。我把它剪掉,直接在上下文中繪製,然後在NSView上顯示爲NSImage。現在我的代碼工作順利。 – Hebbian 2010-08-09 06:55:38