Pregunta

I want to compare two UIColors, however nothing works. I even wrote this function to compare the RGB values of these color:

-(BOOL)compare:(UIColor*)colorA withColor:(UIColor*)colorB{
    CGFloat redA = 0.0, greenA = 0.0, blueA = 0.0, alphaA =0.0;
    [colorA getRed:&redA green:&greenA blue:&blueA alpha:&alphaA];

    CGFloat redB = 0.0, greenB = 0.0, blueB = 0.0, alphaB =0.0;
    [colorB getRed:&redB green:&greenB blue:&blueB alpha:&alphaB];

    NSLog(@"A - %f, %f, %f", redA, greenA, blueA);
    NSLog(@"B - %f, %f, %f", redB, greenB, blueB);

    if (redA == redB && greenA == greenB && blueA == blueB) {
        return  true;
    }else{
        NSLog("false");
        return false;
    }
}

And it return this, which I don't really get:

2014-03-21 21:57:09.481 TextEdit[6863:70b] A - 0.411765, 0.803922, 0.117647
2014-03-21 21:57:09.481 TextEdit[6863:70b] B - 0.411765, 0.803922, 0.117647
2014-03-21 21:57:09.482 TextEdit[6863:70b] false

So it is equal, yet it returns false. Any suggestions?

¿Fue útil?

Solución

You shouldn't use operator == for comparing floating-point numbers (float, double, CGFloat etc) because of the way the number is stored (rounding etc). Instead what you should do is compare if the color components are in a certain range of each other. I think 1.0/255.0 should be ok.

So what you should do is

const CGFloat kRange = 1.0/255.0;
if (fabs(redA - redB) < kRange &&
    fabs(greenA - greenB) < kRange &&
    fabs(blueA - blueB) < kRange &&
    fabs(alphaA - alphaB) < kRange)
{
    return true;
}
else
{
    return false;
}

Otros consejos

I don't have my mac on me, but have you tried:

if([colorA isEqual:colorB]) {
  // true
} else {
  // false
}

If anything, check out this post (How to compare UIColors?). Hopefully that'll shed some more light on the subject for ya.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top