Unable to get pixel color from an image in SwiftUI

293 Views Asked by At

I want to design a draggable color selector view that will select the color of the present pixel. My strategy is, first, to choose the position of the pixel and then, second, get the pixel color. The position has been correctly changed while dragging the view. The color of the view has also been changed but don't understand its manner of changing. I think it doesn't returns the proper color of its pixel. Additionally, when x or y of the CGImage coordinate is less then 0, the getPixelColor() returns 'UIExtendedSRGBColorSpace 0 0 0 0'.

After a long search, I have not get any proper solution to get pixel color in SwiftUI.

The program is given below:

struct ColorSelectorView: View {
    @Binding var position: CGPoint
    @State private var isDragging = false
    @State private var colorPicked = UIColor.black
    var image: UIImage?
    var colorPickedCallBack : (UIColor) -> ()
        
    var body: some View {
        colorSelectorView()
            .onAppear {
                colorPicked = getPixelColor(image: image, point: position) ?? .clear
            }
            .gesture(DragGesture()
                .onChanged { value in
                    self.position.x += CGFloat(Int(value.location.x - value.startLocation.x))
                    self.position.y += CGFloat(Int(value.location.y - value.startLocation.y))
                    colorPicked = getPixelColor(image: image, point: position) ?? .clear
                }
                .onEnded({ value in
                    colorPickedCallBack(colorPicked)
                })
            )
            .offset(x: position.x, y: position.y)
        }
    }

    func getPixelColor(image: UIImage,  point: CGPoint) -> UIColor? {
        guard let pixelData = image.cgImage?.dataProvider?.data else { return nil }
        let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
        let pixelInfo: Int = Int((image.size.width * point.y + point.x) * 4.0)
        let i = Array(0 ... 3).map { CGFloat(data[pixelInfo + $0]) / CGFloat(255) }
        return UIColor(red: i[0], green: i[1], blue: i[2], alpha: 1)
    }
}
0

There are 0 best solutions below