swift - NSGraphicsContext 在 macOS 控制台工具上泄漏内存
问题描述
我正在尝试创建一个小型实用程序类,以帮助在彼此之上绘制一组图像。目前,我有以下代码
struct DrawingLayer {
let image: NSImage
let point: CGPoint
}
class DrawingHelper {
let offscreenRep: NSBitmapImageRep
init() {
guard let offscreenRep = NSBitmapImageRep(bitmapDataPlanes: nil,
pixelsWide: 2500,
pixelsHigh: 2500,
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: .calibratedRGB,
bitmapFormat: .alphaFirst,
bytesPerRow: 0,
bitsPerPixel: 32) else { fatalError() }
self.offscreenRep = offscreenRep
}
func draw(layers: [DrawingLayer], filename: String) {
autoreleasepool {
guard let ctx = NSGraphicsContext(bitmapImageRep: offscreenRep) else { fatalError("Failed to create context") }
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = ctx
layers.forEach { layer in
layer.image.draw(in: CGRect(origin: layer.point, size: CGSize(width: 2500, height: 2500)))
}
NSGraphicsContext.current = nil
NSGraphicsContext.restoreGraphicsState()
guard let data = offscreenRep.representation(using: .png, properties: [:]) else { fatalError() }
do {
try data.write(to: URL(fileURLWithPath: filename))
} catch {
fatalError("\(error)")
}
}
}
我正在实例化这个类,并为我要绘制的每个图像传入一个 DrawLayer 数组。每层代表我想在最终图像中绘制的小图像。我注意到,如果我每次调用绘图函数时都实例化一个 NSGraphicsContext,我的程序的内存使用量就会增加。在 Allocations 分析工具上,我可以让 ImageIO_PNG_Data 对象使用越来越多的内存,但泄漏上没有任何内容。
注意:我设法通过将 NSGraphicsContext 的创建包装在自动释放池中来解决我的问题。我更新了原始代码。
解决方案
推荐阅读
- scala - 如何通过模拟嵌套方法来测试方法?
- python - 为什么这个 if-elif-else 语句打印 42?
- javascript - 获取表格行元素的每个子td的输入html标签的id、名称、类型、值和文本
- sql-server - 根据生效日期选择唯一记录,在终止日期结束
- relational-algebra - 在 σ 中有联合与有两个查询相同吗?
- go - MIME 类型(“text/plain”)不匹配(X-Content-Type-Options: nosniff)
- r - 从列和行匹配“键”的矩阵中提取观察值
- linux - 在 Linux 环境中使用 XlsxWriter
- java - 在 JavaFX 和 Scene Builder 中使用 2D 数组
- r - 从多级序数 logit (clmm) 估计和绘制预测概率