1

I wants to find the pixel colors in the middle of the screen.

extension UIImage {

func getPixelColor(atLocation location: CGPoint, withFrameSize size: CGSize) -> UIColor {
    let pixelPlace: CGPoint = CGPoint(x: location.x, y: location.y)

    let pixelData = self.cgImage!.dataProvider!.data
    let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

    let pixelIndex: Int = ((Int(self.size.width) * Int(pixelPlace.y)) + Int(pixelPlace.x)) * 4

    let r = CGFloat(data[pixelIndex])// / CGFloat(255.0)
    let g = CGFloat(data[pixelIndex+1])// / CGFloat(255.0)
    let b = CGFloat(data[pixelIndex+2])// / CGFloat(255.0)
    let a = CGFloat(data[pixelIndex+3])// / CGFloat(255.0)

    return UIColor(red: r, green: g, blue: b, alpha: a)
}
}

Then I print the color with this.

 let place = CGPoint(x: self.view.center.x , y: self.view.center.y)
    print(yourImageView.image!.getPixelColor(atLocation: place, withFrameSize: self.view.frame.size))

How do I get the center pixel's color? I keep getting other color values than what is in the center. The color detection is functional so I don't believe the problem comes from that.

What I changed (same problem still)

extension UIView {
func getColor(at point: CGPoint) -> 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)
    self.layer.render(in: context)
    let color = UIColor(red:   CGFloat(pixel[0]),
                        green: CGFloat(pixel[1]),
                        blue:  CGFloat(pixel[2]),
                        alpha: CGFloat(pixel[3]))

    pixel.deallocate(capacity: 4)
    return color
}
}

And I access it this way

         let loc = CGPoint(x: yourImageView.center.x, y: yourImageView.center.y)
    var color = yourImageView.getColor(at: loc)
    print(color)
B.Toaster
  • 169
  • 2
  • 13
  • 1
    You should pick the color of your view instead of your image https://stackoverflow.com/a/42687314/2303865 – Leo Dabus Sep 30 '17 at 17:13
  • 1
    https://stackoverflow.com/a/34461183/2303865 – Leo Dabus Sep 30 '17 at 17:19
  • btw your image it is not necessarily the same size of your image view – Leo Dabus Sep 30 '17 at 18:32
  • I made some changes based on the link you sent me to and I posted them in the question above. Unfortunately, I am still having the same problem where the color being chosen is not the center pixel. – B.Toaster Sep 30 '17 at 20:01

0 Answers0