如何比较iOS中几乎相同阴影或范围的两个UIColor? [英] How to compare two UIColor which have almost same shade or range in iOS?

查看:159
本文介绍了如何比较iOS中几乎相同阴影或范围的两个UIColor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个条件,用户可以选择3种颜色,但这些颜色不应该相互匹配,问题是用户可以从托盘中为所有3个字段选择相似的颜色。

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.

我正在尝试下面的代码,这里color2的颜色与color1略有不同: -

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");
    }

输出:'不等于'
这是正确的逻辑因为它比较RGB值,但我想检查它的范围,让我知道是否有人知道如何比较相似的颜色。

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.

推荐答案

您需要一个容差,其价值只能由您决定:

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");
}

这篇关于如何比较iOS中几乎相同阴影或范围的两个UIColor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆