I have seen people do this in objective-c, but I am having trouble with this in swift. I have gotten the color of a pixel from a picture, but now I need to take the individual red, green, and blue values. Here is what I have (h, w, and rgb are integers and image.getPixelColor(CGPoint) returns a UIColor):
xArry[h][w][rgb] = image.getPixelColor(CGPoint(x: w, y: h))
How do I change this UIColor into the red, green, and blue values? Thanks!
You can use CGColorGetComponents to get array of color of a CGColor (not tested in swift3)
You can find also number of color components of that color with
You have to verify number of components before get values. Gray color has 2 components (grey & alpha), rgb colors have 4 components: R, G, B, A
https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGColor/index.html#//apple_ref/c/func/CGColorGetNumberOfComponents
for UIColor you can just use getRed method:
Untested but this should work. Just found it:
You can convert UIColor to CIColor and then extract the color components from it as follow:
Update: Xcode 8.3.2 • Swift 3.1
usage:
You can also use the function getRed() and create an extension to extract the components as follow but the result would be optional:
Usage