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