objective-c - 使用 cocoa 绘制 NSImage

标签 objective-c macos cocoa core-graphics nsview

目前我正在 NSView 上使用贝塞尔路径绘制一些形状。绘图代码在 drawRect: 方法上执行并最终创建图像。

我不想在任何地方向用户显示此 View 。然而,据我所知,只有当我们将 View 添加到 super View ,然后在 NSView 上调用 display 或 displayNeedsUpdate 方法时,才会调用 drawRect: 方法。

我的要求是创建我所需绘图的图像。

我们有什么办法可以直接绘制图像,而不是在 NSView 上绘制并将其转换为 PNG 吗?

最佳答案

您必须创建一个 NSBitmapImageRep 并通过指定您的 View 框架来使用 bitmapImageRepForCachingDisplayInRect:

将绘制位图图像表示。

然后,您只需使用 representationUsingType:NSPNGFileType properties:nil 并将结果写入文件即可。

以下示例摘自 cocoa 与爱的教程:Advanced drawing using AppKit

NSRect iconViewFrame = iconView.frame;
[iconView setFrame:[iconView nativeRect]];

NSBitmapImageRep *bitmapImageRep =
    [iconView bitmapImageRepForCachingDisplayInRect:[iconView frame]];
[iconView
    cacheDisplayInRect:[iconView bounds]
    toBitmapImageRep:bitmapImageRep];
[[bitmapImageRep representationUsingType:NSPNGFileType properties:nil]
    writeToURL:[savePanel URL]
    atomically:YES];

[iconView setFrame:iconViewFrame];

他们还建议:

Creating your own NSBitmapImageRep, setting the NSGraphicsContext using graphicsContextWithBitmapImageRep:, locking focus yourself and invoking drawRect: directly will avoid these issues and is more flexible. But it would have been more work so I didn't bother for this sample project (I mostly put this export code into the app so I could create the app's icon).

因此您可以选择最适合您需求的解决方案。

关于objective-c - 使用 cocoa 绘制 NSImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15769929/

相关文章:

objective-c - 将 NSImage 初始化为静态对象

objective-c - 使用助手发布的 NSUserNotification 打开主应用程序

iphone - 实现树结构UITableview

visual-studio - 是什么阻止 Cocotron 在 Visual Studio 而不是 Mac OS X 上交叉编译?

objective-c - 如何创建测试以确保没有保留周期?

c - OpenCv Makefile Undefined symbols for architecture x86_64 错误

macos - MAC上的grep特定文件类型

objective-c - 如何允许使用 Mac 应用程序上的标准下载系统从 WebView 下载?

ios - 从可变数组访问数据

objective-c - 直接分配和分配时,UIImageView/UILabel 属性始终为 nil