从iPad Pro和iPad获取像素颜色

时间:2018-03-16 21:52:58

标签: ios swift

我从另一篇文章中发现的以下扩展程序可以很好地从屏幕图像上的触摸点获取像素RGB值。它适用于iPad但不适用于iPad Pro。在pro上,无论触摸位置如何,它都会返回相同的固定值,而不是预期的RGBA。为什么这对专业人士不起作用?我怀疑与CGBitmapInfo设置有关但无法从Apple的文档中找到它。

extension UIImageView {
    func getPixelColorAt_ext(point:CGPoint) -> (clr: UIColor, red: Int, green: Int, blue: Int) {

    let pixel = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: 4)
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
    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)
    layer.render(in: context!)
    let r = Int(pixel[0])
    let g = Int(pixel[1])
    let b = Int(pixel[2])
    let color = UIColor(red: CGFloat(r)/255.0,
                        green: CGFloat(g)/255.0,
                        blue: CGFloat(b)/255.0,
                        alpha: 1.0)
    pixel.deallocate(capacity: 4)
    return (clr: color, red: r, green: g, blue: b)
    }
}

1 个答案:

答案 0 :(得分:0)

问题在于解除分配,这在iPad Pro上发生的速度要快得多。通过在调用pixel.deallocate之前添加let r = Int(pixel [0])等来修复,如上面更正的版本所示。