objective-c – 从CGImageRef创建NSImage会导致图像像素大小加倍

capture是从对CGWindowListCreate
Image()的调用返回的CG
ImageRef.当我尝试通过initWithCGImage直接将它变成NSImage时:size:它的大小神秘地增加了一倍.如果我从捕获手动创建NSBitmapImageRep然后将其添加到空NSImage一切正常.

我的硬件设置是视网膜MBP非视网膜外部显示器.捕获发生在非视网膜屏幕上.

NSLog(@"capture image size: %d %d", CGImageGetWidth(capture), CGImageGetHeight(capture));
NSLog(@"logical image size: %f %f", viewRect.size.width, viewRect.size.height);

NSBitmapImageRep *debugRep;
NSImage *image;

//
// Create NSImage directly

image = [[NSImage alloc] initWithCGImage:capture size:NSSizeFromCGSize(viewRect.size)];

debugRep = [[image representations] objectAtIndex:0];
NSLog(@"pixel size, NSImage direct: %d %d", debugRep.pixelsWide, debugRep.pixelsHigh);

//
// Create representation manually

NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:capture];
image = [[NSImage alloc] initWithSize:NSSizeFromCGSize(viewRect.size)];
[image addRepresentation:imageRep];
[imageRep release];

debugRep = [[image representations] objectAtIndex:0];
NSLog(@"pixel size, NSImage + manual representation: %d %d", debugRep.pixelsWide, debugRep.pixelsHigh);

日志输出:

capture image size: 356 262
logical image size: 356.000000 262.000000
pixel size, NSImage direct: 712 524
pixel size, NSImage + manual representation: 356 262

这是预期的行为吗?

最佳答案 适用于initWithCGImage的
documentation:size:states:

You should not assume anything about the image, other than that
drawing it is equivalent to drawing the CGImage.

最后,我继续直接使用NSBitmapImageRep实例.

点赞