Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

objective c - How to compare two UIColor which have almost same shade or range in iOS?

I have a condition in my app where user can choose 3 colors, but those colors should not match with each other, the problem is user can choose the similar color from the pallet for all 3 fields.

I'm trying below code, here color2 has slightly different value of 'green' than color1 :-

UIColor *color1 = [UIColor colorWithRed:1 green:(CGFloat)0.4 blue:1 alpha:1];
UIColor *color2 = [UIColor colorWithRed:1 green:(CGFloat)0.2 blue:1 alpha:1];

 if ([color1 isEqual:color2]) {
        NSLog(@"equals");
    }else {
        NSLog(@"not equal");
    }

output: 'not equal' This is correct by logic because it compares RGB value but I want to check range of it, Let me know if anyone knows how to compare the similar colors.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need a tolerance, the value of which, only you can decide:

- (BOOL)color:(UIColor *)color1
isEqualToColor:(UIColor *)color2
withTolerance:(CGFloat)tolerance {

    CGFloat r1, g1, b1, a1, r2, g2, b2, a2;
    [color1 getRed:&r1 green:&g1 blue:&b1 alpha:&a1];
    [color2 getRed:&r2 green:&g2 blue:&b2 alpha:&a2];
    return
        fabs(r1 - r2) <= tolerance &&
        fabs(g1 - g2) <= tolerance &&
        fabs(b1 - b2) <= tolerance &&
        fabs(a1 - a2) <= tolerance;
}

...

UIColor *color1 = [UIColor colorWithRed:1 green:(CGFloat)0.4 blue:1 alpha:1];
UIColor *color2 = [UIColor colorWithRed:1 green:(CGFloat)0.2 blue:1 alpha:1];

if ([self color:color1 isEqualToColor:color2 withTolerance:0.2]) {
    NSLog(@"equals");
} else {
    NSLog(@"not equal");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...