目前我正在 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/