代码之家  ›  专栏  ›  技术社区  ›  Dan Rosenstark

获取随机颜色但避免深色:帮助我的算法

  •  8
  • Dan Rosenstark  · 技术社区  · 14 年前

    我正试图得到一个随机的颜色。我已经使用蛮力完成了这项工作,但这种方法似乎过于繁琐(尽管分布相当均匀):

    - (UIColor *) getRandomColor {
     // GOAL: reject colors that are too dark
     float total = 3;
     float one = arc4random() % 256 / 256.0;
     total -= one;
     float two = arc4random() % 256 / 256.0;
     total -= two;
     float three = total; // UIColor will chop out-of-range nums
    
     NSMutableArray *threeFloats = [[[NSMutableArray alloc] initWithObjects:[NSNumber numberWithFloat:one], [NSNumber numberWithFloat:two], [NSNumber numberWithFloat:three], nil] autorelease];
    
     NSNumber *red, *green, *blue;
     red = [threeFloats objectAtIndex:arc4random() % [threeFloats count]];
     [threeFloats removeObject:red];
     green = [threeFloats objectAtIndex:arc4random() % [threeFloats count]];
     [threeFloats removeObject:green];
     blue = [threeFloats lastObject];
    
     return [UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:1];
    }
    

    怎样才能更好呢?我想要红色、绿色和蓝色的均匀分布,不要太暗(否则我会随机抽取三个数字,然后处理掉)。

    3 回复  |  直到 14 年前
        1
  •  15
  •   drawnonward    14 年前
    + (UIColor *)colorWithHue:(CGFloat)hue saturation:(CGFloat)saturation brightness:(CGFloat)brightness alpha:(CGFloat)alpha;
    
    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
    

    如果白色是可以的,那么做饱和度喜欢色调而不是亮度。

        2
  •  2
  •   Jerry Coffin    14 年前

    我可能会为色调、饱和度和亮度(或hsb)生成(伪)随机数,亮度(或亮度)限制在您认为合理的范围内,然后 convert that to RGB .

        3
  •  1
  •   sukru    14 年前

    此方法可以帮助您快速随机生成明亮的颜色:

    1 - Pick a random integer between 0-2
    2 - If it is 0, set Red to Random(0.75-1.0), Green and Blue to Random(0.0-1.0)
    2 - If it is 1, set Green to Random(0.75-1.0), Red and Blue to Random(0.0-1.0)
    2 - If it is 2, set Blue to Random(0.75-1.0), Green and Red to Random(0.0-1.0)