我不太确定你的设置到底是什么。在自定义视图中绘制图像与使用NSImageView
。此外,可能(或可能不是)图层支持的自定义视图与图层托管视图不同。
你有很多正确的元素,但它们都混在一起了。在任何情况下,您都不必将注意力锁定在某个NSImage
。那是为了画画into an NSImage
。另外,还有一个自定义视图,它是从NSView
不必打电话super
in its -drawRect:
. NSView
不画任何东西。
要在自定义视图中绘制图像,请尝试:
- (void) drawRect:(NSRect)dirtyRect
{
CGImageRef cgImage = /* ... */;
NSSize maxSize = /* ... */;
CGContextRef ctx = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
CGRect renderRect = CGRectMake(0., 0., maxSize.width, maxSize.height);
CGContextDrawImage(ctx, renderRect, cgImage);
CGImageRelease(cgImage);
}
如果你有一个NSImageView
,那么您不需要自定义视图或任何绘图方法或代码。只需在获取图像或生成图像所需的信息时执行以下操作:
NSImageView* imageView = /* ... */; // Often an outlet to a view in a NIB rather than a local variable.
CGImageRef cgImage = /* ... */;
NSImage* image = [[NSImage alloc] initWithCGImage:cgImage size:/* ... */];
imageView.image = image;
CGImageRelease(cgImage);
如果您使用图层托管视图,则只需设置CGImage
作为图层的内容。同样,每当您获得图像或生成图像所需的信息时,您都会执行此操作。它不在-drawRect:
.
CALayer* layer = /* ... */; // Perhaps someView.layer
CGImageRef cgImage = /* ... */;
layer.contents = (__bridge id)cgImage;
CGImageRelease(cgImage);