用CGImage绘制图像?

Heb*_*ian 5 cocoa core-graphics nsview quartz-2d

我有一个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);
}
Run Code Online (Sandbox Code Playgroud)

它出什么问题了?

Ste*_*out 1

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