使用位图 CGContext 绘图不断增加的内存使用量



我正在尝试在CGLayer中移动子区域内容。主要思想是,我首先将源区域(我要移动的部分(绘制到新创建的位图 CGContext 中,然后从中制作一个 CGImage,并将其绘制回不同位置的原始图层。以下是有问题的代码片段:

let size = src.size
//create the bitmap context
UIGraphicsBeginImageContextWithOptions(size, true, 0)
guard let ctx = UIGraphicsGetCurrentContext() else { return }
ctx.saveGState()
//flip the context to match the origin position of UIKit
ctx.translateBy(x: 0, y: size.height)
ctx.scaleBy(x: 1.0, y: -1.0)
//draw the source part of the layer into the bitmap context
let offset = CGPoint(x: -src.origin.x, y: -src.origin.y)
let iRect = CGRect(origin: offset, size: self.shellBounds.size)
let bounds = CGRect(origin: .zero, size: size)
ctx.clip(to: bounds)
ctx.draw(layer, in: iRect)
//make a CGImage of the contents
let image = ctx.makeImage()!
//draw this part back to the layer (context is obtained from layer)
context.saveGState()
context.clip(to: target)
context.setBlendMode(.copy)
context.draw(image, in: target)
context.restoreGState()
ctx.restoreGState()
UIGraphicsEndImageContext()

这按预期工作。但是,问题是,每次调用时内存使用量都会不断增加。

记忆增加可能是因为图像的制作。但它似乎没有在最后发布。我的代码片段有什么问题?我需要手动释放创建的镜像吗?如果是这样,我该怎么做,因为 Swift 使用 ARC 作为核心图形,如文档中所述?

事实证明,当再次将生成的图像绘制到图层中时,内存问题就开始了(当将生成的图像绘制回图层的部分被注释掉时,内存永远不会再增加(。

由于CGLayer的内部实现是未知的,因此很难知道此问题的确切原因。我所做的只是放弃这种方法并以另一种方式实现它。

最新更新