1

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)
    }
}
Jabed Dhali
  • 167
  • 6
  • Can u check this https://stackoverflow.com/a/56723477/1638892 – Wo_0NDeR ᵀᴹ Dec 11 '22 at 13:48
  • For using it, I have to convert UIImage to UIView. But I have not found any solution of it, that is why I didn't use it. Could you please suggest me any way to do it or any alternatives? – Jabed Dhali Dec 12 '22 at 04:12

0 Answers0