2

I have a SwiftUI image displayed like this:

Image("Map")
     .resizable()
     .gesture(
        DragGesture(minimumDistance: 0, coordinateSpace: .global)
          .onChanged { value in
              self.position = value.location
              print(position)
              let color = getColor(at: position)
              print(color)
           }
           .onEnded { _ in
              self.position = .zero
           }
        )

and a getColor function:

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)
        let color = 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()
        return color
    }

When I launch the app and touch the Image, the position is well displayed on the console but the color returns 0 0 0 0, example:

(262.3333282470703, 691.6666564941406)
UIExtendedSRGBColorSpace 0 0 0 0

After a long search, I didn't find a way to get a pixel color from an Image in SwiftUI, if someone has a solution or can help me, it would be really nice.

Thank you in advance.

Shinryu
  • 21
  • 3
  • https://stackoverflow.com/questions/25146557/how-do-i-get-the-color-of-a-pixel-in-a-uiimage-with-swift – Azhagusundaram Tamil Apr 09 '21 at 11:15
  • Hi, thanks for your answer but this solution is for UIKit, not SwiftUI right ? – Shinryu Apr 09 '21 at 11:21
  • SwiftUI does not expose a CoreGraphics API context. Since you are trying to get the values via CGContext (UIKit way), that is probably root of the issue you are having. Another approach to your problem could be using CoreImage API's, an example [here](https://medium.com/swlh/swiftui-read-the-average-color-of-an-image-c736adb43000) – Burak Akkaş Apr 09 '21 at 13:13

0 Answers0