【问题标题】:Why does my CGImage not display correctly after setNeedsDisplay为什么我的 CGImage 在 setNeedsDisplay 后无法正确显示
【发布时间】:2016-06-12 11:46:21
【问题描述】:

我正在我的应用程序中绘制一个 colorWheel。我通过在单独的函数中生成 CGImage 并在 drawRect 中使用 CGContextDrawImage 将其放在屏幕上来做到这一点。

在最初的演示中,它看起来不错,但在我调用 setNeedsDisplay(或 setNeedsDisplayInRect)之后,图像变黑/失真。我一定在做一些愚蠢的事情,但看不到什么。

DrawRect 代码如下:

override func drawRect(rect: CGRect) {

    if let context = UIGraphicsGetCurrentContext() {

        let wheelFrame = CGRectMake(0,0,circleRadius*2,circleRadius*2)
        CGContextSaveGState(context)

            //create clipping mask for circular wheel
        CGContextAddEllipseInRect(context, wheelFrame)
        CGContextClip(context)

            //draw the wheel
        if colorWheelImage != nil { CGContextDrawImage(context, CGRectMake(0,0,circleRadius*2,circleRadius*2), colorWheelImage) }
        CGContextRestoreGState(context)

            //draw a selector element
        self.drawSliderElement(context)
    }
}

CG图像生成函数:

func generateColorWheelImage() {

    let width       = Int(circleRadius*2)
    let height      = Int(circleRadius*2)

    var pixels = [PixelData]()

    for yIndex in 0..<width {
        for xIndex in 0..<height {
            pixels.append(colorAtPoint(CGPoint(x: xIndex, y: yIndex)))
        }
    }

    let rgbColorSpace   = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo      = CGBitmapInfo.ByteOrderDefault

    let bitsPerComponent: Int   = 8
    let bitsPerPixel: Int       = 24

    let renderingIntent = CGColorRenderingIntent.RenderingIntentDefault

    assert(pixels.count == Int(width * height))

    var data = pixels

    let providerRef = CGDataProviderCreateWithData(nil, data, data.count * sizeof(PixelData), nil)

    colorWheelImage = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, width * Int(sizeof(PixelData)), rgbColorSpace, bitmapInfo, providerRef, nil, true,renderingIntent)

}

【问题讨论】:

    标签: ios swift core-graphics cgcontextdrawimage


    【解决方案1】:

    当我开始在 ipad 而不是模拟器上运行代码并收到 BAD_ACCESS_ERROR,而不是看到扭曲的图像时,我终于找到了这个问题的答案(这里:https://stackoverflow.com/a/10798750/5233176)。

    正如答案所解释的:'[The] CMSampleBuffer 直接用于创建 CGImageRef,因此一旦释放缓冲区,[the] CGImageRef 将变得无效。'

    因此问题出在这一行:

        let providerRef = CGDataProviderCreateWithData(nil, data, data.count * sizeof(PixelData), nil)
    

    并且可以通过使用缓冲区的副本来解决问题,如下所示:

        let providerData    = NSData(bytes: data, length: data.count * sizeof(PixelData))
        let provider        = CGDataProviderCreateWithCFData(providerData)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-03
      • 2020-08-29
      • 1970-01-01
      • 2020-04-06
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      相关资源
      最近更新 更多