我有我的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);
}
什麼不好的代碼?
- 感謝&方面 -
感謝您的快速回復。 因此,我應該將生成的CGImage更改爲NSImage以便將其繪製到NSView中?所以然後我可以使用通用繪製方法,如 [myNSImage drawInRect:fromRect:operation:fraction] – Hebbian 2010-08-06 14:16:54
您可以這樣做,是的。除非你不需要圖像作爲Core Graphics圖像,否則我會建議你使用NSImage來完成你的任務。 – SteamTrout 2010-08-06 14:26:59