Drawing Image with CGImage?

Hebbian picture Hebbian · Aug 6, 2010 · Viewed 8.5k times · Source

I have a CGImageRef and I want to display it on an NSView. I already have an CGImageRef from source path but the following doesn't work:

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

What's wrong with it?

Answer

Peter Hosey picture Peter Hosey · Aug 7, 2010
CGImageRef myDrawnImage = [self createCGImageRefFromFile:thePath];

Now you have your image.

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

Now you have your view's context. You have everything you need to draw the image.

CGContextRef myContextRef = CreateARGBBitmapContext(myDrawnImage);

Wait, what?

myDrawnImage = CGBitmapContextCreateImage(myContextRef);

O…kay… now you have captured the contents of a context that nothing has drawn in, forgetting about (and leaking) your loaded image by replacing it with a blank image.

CGContextDrawImage(context, imageRect, myDrawnImage);

You draw the blank image.

Cut out the creation of a bitmap context and the creation of an image of the contents of that context, and just draw the image you loaded into the context for your view.

Or use NSImage. That would be a two-liner.