2

我正在我的应用程序中绘制一个 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)

}
4

1 回答 1

0

当我开始在 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)
于 2016-08-18T14:51:38.247 回答