Sort Colors (Objective-C)

后端 未结 2 959
离开以前
离开以前 2021-02-14 14:54

I\'m doing this sort of thing:

- (NSArray*)colors {
    float divisor = .3333;
    NSMutableArray *retVal = [NSMutableArray array];
    for (float one=0; one <         


        
2条回答
  •  有刺的猬
    2021-02-14 15:20

    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;
    }];
    

    You can access the components (HSBA) like this in iOS 4.x:

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

    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.

提交回复
热议问题