2

How to get pixel colour on touch on the device, the below code works well on simulator but on device it returns wrong value. I don't know what was wrong

To get pixel colour on touch i used the code

func getPixelColorAtPoint(point:CGPoint, sourceView: UIView) -> UIColor{

    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)
    sourceView.layer.render(in: context!)
    let color: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)
    return colour
}

referred from How to get the pixel color on touch?

Any suggestions would be helpful

Community
  • 1
  • 1
Raghuram
  • 1,651
  • 2
  • 12
  • 17
  • 1
    In what way is it wrong? Is it selecting a color from a different part of the image? Is it color shifted? Dramatically or subtly? Does it always return the same value? Is that value zero? I recommend simplifying your image, first to a solid black, then to each of solid red, green, blue. Then create a grid of solid color. Testing each of these setups will let you discover precisely what kind of "wrong" you're encountering. (First you are testing that zero is zero; then that basic colors are correct; then that positions are correct.) – Rob Napier Mar 18 '17 at 14:49

0 Answers0