我点击图片返回像素颜色。这很好但我发现它在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
答案 0 :(得分:2)
CGContext(data: pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, ...)
创建一个由四个字节(每个颜色组件一个)备份的图形上下文,因此您必须传递一个UInt8
数组:
let pixel = UnsafeMutablePointer<UInt8>.allocate(capacity: 4)
在您的情况下,只会设置第一个CGFloat
的前4个字节,所有剩余数据未定义(可能会导致nan
或一些任意值)。即使你没有得到
nan
,价值观将是错误的。