I have a func to retrieve the RGB of an image.
import Foundation
func findColors(_ image: UIImage) -> [UIColor] {
let pixelsWide = Int(image.size.width)
let pixelsHigh = Int(image.size.height)
guard let pixelData = image.cgImage?.dataProvider?.data else { return [] }
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
var imageColors: [UIColor] = []
for x in 0..<1 {
for y in 0..<1 {
let point = CGPoint(x: x, y: y)
let pixelInfo: Int = ((pixelsWide * Int(point.y)) + Int(point.x)) * 4
let color = UIColor(red: CGFloat(data[pixelInfo]) / 255.0,
green: CGFloat(data[pixelInfo + 1]) / 255.0,
blue: CGFloat(data[pixelInfo + 2]) / 255.0,
alpha: CGFloat(data[pixelInfo + 3]) / 255.0)
imageColors.append(color)
}
}
return imageColors
}
I'm trying to display that RGB as an actual color in the UI. I tried the below code, but giving me error. Could you please suggest how to call the func findColors properly?
let image = UIImage(named: "Fish.jpg")!
struct ContentView: View {
var body: some View {
Color(findColors(image))
.frame(width:10, height: 10)
.position(x: 40, y: 40)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
You're returning an array of colors from your findColors function, and there's no SwiftUI Color view that accepts an array as parameter.
It's unclear why you're returning an array here, since your code only extracts color from one pixel. It seems like what you really want is an optional color returned from the function. In that case, you'd need additional code in your ContentView to handle the two cases: one where a color is returned, and the other where no color is returned.