【问题标题】:Ever increasing memory usage with bitmap CGContext drawing使用位图 CGContext 绘图不断增加内存使用量
【发布时间】:2019-02-20 13:46:04
【问题描述】:

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

    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()

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

内存增加可能是由于图像的制作。但是最后好像没有发布。我的代码 sn-p 有什么问题?我需要手动发布创建的图像吗?如果是这样,我该怎么做,因为 Swift 如文档中所述将 ARC 用于核心图形?

【问题讨论】:

  • makeImage() 是做什么的?我们可以看到代码吗?
  • @AshleyMills makeImage() 来自官方 API。它的功能是从上下文“ctx”制作图像(CGImage)。我不认为有代码可以看,因为它不是开源的。
  • 为什么投反对票?我的问题有问题吗?

标签: ios swift memory core-graphics cglayer


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 2017-01-13
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多