2010-08-06 90 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