我在我的应用中绘制了一个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)
}
}
CGimage生成功能:
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)
}
答案 0 :(得分:0)
当我开始在ipad而不是模拟器上运行代码并收到BAD_ACCESS_ERROR时,我终于找到了这个问题的答案(这里是https://stackoverflow.com/a/10798750/5233176),而不是看到扭曲的图像。
正如答案所解释的:'[CMS] CMSampleBuffer直接用于创建CGImageRef,因此一旦释放缓冲区,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)