首页 > 解决方案 > 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 的创建包装在自动释放池中来解决我的问题。我更新了原始代码。

标签: swiftmacoscore-graphicsnsimage

解决方案


推荐阅读