Swift 颜色 space iPhone 5 与 iPhone 5s 或 5se 不同

Swift Color space different on iPhone 5 compared to iPhone 5s or 5se

我点击一个图像return一个像素颜色。这很好用,但我发现它不适用于 iPhone 5。它适用于 iPhone 5s、5SE 和所有其他尺寸。我不懂为什么。 以下代码在 iPhone 5.

上将红色和蓝色作为 nan
//  returns the color data of the pixel at the currently selected point

func getPixelColorAtPoint(_ point:CGPoint)-> UIColor{
 let pixel = UnsafeMutablePointer<CGFloat>.allocate(capacity: 4)
 let colorSpace = CGColorSpaceCreateDeviceRGB()
 let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
 if let context = CGContext(data: pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue){
   context.translateBy(x: -point.x, y: -point.y)
   torsoImage.layer.render(in: context)
 }
 let pColor:UIColor = UIColor(red: CGFloat(pixel[0])/255.0, green: CGFloat(pixel[1])/255.0, blue: CGFloat(pixel[2])/255.0, alpha: CGFloat(pixel[3])/255.0)

 pixel.deallocate(capacity: 4)
 print("Colour touch is \(pColor)")
 return pColor
}

//Colour touch is UIExtendedSRGBColorSpace nan 1.94443e+12 nan 1.48678e-42
CGContext(data: pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, ...)

创建一个由四个 字节 支持的图形上下文(每个颜色分量一个),因此您必须传递一个数组 UInt8:

let pixel = UnsafeMutablePointer<UInt8>.allocate(capacity: 4)

你的情况是,只有第一个 CGFloat 的前 4 个字节会被设置,所有剩余的数据都是 undefined(并且可能导致 nan 或某个任意值)。即使得不到 nan,数值会出错。