排序颜色(Objective-C) [英] Sort Colors (Objective-C)

查看:152
本文介绍了排序颜色(Objective-C)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做这类事情:

- (NSArray*)colors {
    float divisor = .3333;
    NSMutableArray *retVal = [NSMutableArray array];
    for (float one=0; one <= 1.0f; one += divisor) {
        for (float two = 0; two <= 1.0f; two += divisor) {
            for (float three = 0; three <= 1.0f; three += divisor) {
                UIColor *color = [UIColor colorWithRed:one green:two blue:three alpha:.5];
                // also bad
                // UIColor *color = [UIColor colorWithHue:one saturation:two brightness:three alpha:.5];
                [retVal addObject:color];
            }
        }
    }
    return retVal;
}

并且,正如我所怀疑的那样,颜色出现严重失调(至眼)。红色不是红色,紫色不是紫色,等等。

and, as I suspected, the colors come out horribly out of order (to the eye). The reds are not with the reds, purples not with the purples, etc.

没有简单的方法来创建不同颜色的列表,根据人类标准很好地分组比如,看起来很蓝?

Is there no easy way to create a list of diverse colors, nicely grouped according to human criteria like, "that looks blue?"

推荐答案

这很有效。你有很多重复的颜色,这无济于事。见下文:

This worked quite well. It will NOT help the fact that you have a lot of repeated colors. See below:

NSArray *sorted = [[dict allValues] sortedArrayUsingComparator:^NSComparisonResult(UIColor* obj1, UIColor* obj2) {
    float hue, saturation, brightness, alpha;
    [obj1 getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
    float hue2, saturation2, brightness2, alpha2;
    [obj2 getHue:&hue2 saturation:&saturation2 brightness:&brightness2 alpha:&alpha2];
    if (hue < hue2)
        return NSOrderedAscending;
    else if (hue > hue2)
        return NSOrderedDescending;

    if (saturation < saturation2)
        return NSOrderedAscending;
    else if (saturation > saturation2)
        return NSOrderedDescending;

    if (brightness < brightness2)
        return NSOrderedAscending;
    else if (brightness > brightness2)
        return NSOrderedDescending;

    return NSOrderedSame;
}];

您可以在 iOS 4.x中访问这样的组件(HSBA):

    CGFloat *components = (CGFloat *)CGColorGetComponents([color CGColor]);
    float hue = components[0];
    float saturation = components[1]; // etc. etc.

为避免重复颜色:你可以放NSMutableDictionary中的元素,键入其色调饱和度 - 亮度(每个舍入到最接近的.10)...然后从THAT获取数组,然后排序。

To avoid repeating colors: you can put the elements in an NSMutableDictionary, keyed on something like their hue-saturation-brightness (each rounded to the nearest .10)... then you get the array from THAT, and then sort.

这篇关于排序颜色(Objective-C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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