我正在尝试在 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 用于核心图形?