且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 CGImageRef 图像在 NSView 中显示图像

更新时间:2023-11-26 12:43:34

我不太清楚您的设置究竟是什么.在自定义视图中绘制图像与使用 NSImageView 是不同的.此外,可以(也可以不)支持图层的自定义视图与托管图层的视图不同.

I'm not quite sure what exactly your setup is. Drawing an image in a custom view is a separate thing from using an NSImageView. Also, a custom view that may (or may not) be layer-backed is different from a layer-hosting view.

您有很多正确的元素,但它们都混在一起了.在任何情况下,您都不必将焦点锁定在 NSImage 上.这是用于绘制一个NSImage.此外,从 NSView 继承的自定义视图不必在其 -drawRect: 中调用 super.NSView 不绘制任何东西.

You have a lot of the right elements, but they're all mixed up together. In no case do you have to lock focus on an NSImage. That's for drawing into an NSImage. Also, a custom view that subclasses from NSView doesn't have to call super in its -drawRect:. NSView doesn't draw anything.

要在自定义视图中绘制图像,请尝试:

To draw an image in a custom view, try:

- (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,那么你就不需要自定义视图或任何绘图方法或代码.只需在获取图像或生成图像所需的信息时执行以下操作:

If you have an NSImageView, then you don't need a custom view or any drawing method or code. Just do the following at the point where you obtain the image or the information necessary to generate it:

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: 中.

If you're working with a layer-hosting view, you just need to set the CGImage as the layer's content. Again, you do this whenever you obtain the image or the information necessary to generate it. It's not in -drawRect:.

CALayer* layer = /* ... */; // Perhaps someView.layer
CGImageRef cgImage = /* ... */;
layer.contents = (__bridge id)cgImage;
CGImageRelease(cgImage);