2010-07-28 28 views
8

Rastgele bir renk almaya çalışıyorum. Ben kaba kuvvet kullanarak yaptım ama (dağıtım oldukça bile olsa) bu yöntem aşırı zahmetli görünüyor: NasılgetRandomColor ancak koyu renklerden kaçının: Algoritıma yardımcı olun

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

iyisini edilebilir? Ben kırmızı, yeşil ve mavi bir eşit dağılımını istiyorum ve çok karanlık bir şey (aksi takdirde üç rastgele sayıları alıp onunla yapalım).

cevap

15
+ (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 

Beyaz renkte değilse, parlaklık yerine renk tonu gibi doygunluk yapın.

1

Bu yöntem hızlı rastgele parlak renkler oluşturmaya yardımcı olabilir:

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) 
2

muhtemelen hafiflik tonu, doygunluk ve hafiflik (veya HSB) için (sözde) rastgele sayılar oluşturmak (veya parlaklık ediyorum) makul bulduğunuz herhangi bir aralıkla sınırlı, daha sonra convert that to RGB.

İlgili konular