4

我有一个CGImageRef,我想将它显示在一个NSView. 我已经有一个CGImageRef源路径,但以下不起作用:

- (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);
}

它出什么问题了?

4

2 回答 2

4
CGImageRef myDrawnImage = [self createCGImageRefFromFile:thePath];

现在你有了你的形象。

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

现在您有了视图的上下文。您拥有绘制图像所需的一切。

CGContextRef myContextRef = CreateARGBBitmapContext(myDrawnImage);

等等,什么?

myDrawnImage = CGBitmapContextCreateImage(myContextRef);

哦……好吧……现在您已经捕获了一个没有任何内容的上下文的内容,通过用空白图像替换它来忘记(并泄漏)您加载的图像。

CGContextDrawImage(context, imageRect, myDrawnImage);

您绘制空白图像。

删除位图上下文的创建和该上下文内容的图像的创建,只需将您加载到上下文中的图像绘制为您的视图。

或者使用 NSImage。那将是一条两条线。

于 2010-08-06T22:35:01.223 回答
1

是的,您实际上并没有绘制图像。您需要做的就是使用CGContextDrawImage而不是创建一个空的位图上下文。

于 2010-08-06T13:20:14.330 回答