I'd like to check the color set for a background on a UIImageView. I've tried:
if(myimage.backgroundColor == [UIColor greenColor]){
...}
else{
...}
but that doesn't work, even when I know the color is green, it always falls into the else part.
Also, is there a way to output the current color in the debug console.
p [myimage backgroundColor]
and
po [myimage backgroundColor]
don't work.
Here is an extension to switch to the RGC Space Color in Swift:
}
I had same problem in my color game and i solved that by using simple difference equation in RGB colors you can quick take a look that short code sample ColorProcess from here
its like victors answer
Instead of that code sample you can use
and of course if it returns 0 that means you are comparing too similar color. return range is something like (0.0f - 1.5f)..
Extension to UIColor, using Swift 2.2 features. Note however that because the R G B A values are compared, and these are CGFloat, rounding errors can make that the colours are non returned as equal if they are not exactly the same (e.g. they have not been originally created using the exact same properties in the init(...)!).
As zoul pointed out in the comments,
isEqual:
will returnNO
when comparing colors that are in different models/spaces (for instance#FFF
with[UIColor whiteColor]
). I wrote this UIColor extension that converts both colors to the same color space before comparing them:I have converted raf's answer to Swift 4 (lots of changes in the
CGColor
API), removed force unwrapping and decreased indentation thanks to generous use ofguard
:I'm using this extension which is working for me in all cases.
Hope helps some one.
Note:
#ffffff
does equal[UIColor whiteColor]
by this extension