2013-07-18 157 views
2

我有一個drawRect方法內的for循環,它繪製了多個圓圈來填充屏幕。我試圖讓它每個圈都有一個新的隨機筆畫。出於某種原因沒有出現。這裏是我的randomColor方法:爲什麼這種隨機顏色方法不起作用?

-(UIColor *) randomColor 
{ 
    int red, green, blue, alpha; 

    red = arc4random_uniform(255); 
    green = arc4random_uniform(255); 
    blue = arc4random_uniform(255); 
    alpha = arc4random_uniform(255); 

    UIColor *colorToReturn = [[UIColor alloc] initWithRed:red green:green blue:blue alpha:alpha]; 

    return colorToReturn; 
} 

,我嘗試在這裏實現它:

-(void) drawRect:(CGRect)rect 
{ 
    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    CGRect bounds = [self bounds]; 

    // Firgure out the center of the bounds rectangle 
    CGPoint center; 
    center.x = bounds.origin.x + bounds.size.width/2.0; 
    center.y = bounds.origin.y + bounds.size.height/2.0; 

    // The radius of the circle should be nearly as big as the view 
    float maxRadius = hypot(bounds.size.width, bounds.size.height)/2.0; 

    // The thickness of the line should be 10 points wide 
    CGContextSetLineWidth(ctx, 10); 

    // The color of the line should be gray (red/green/blue = 0.6, alpha = 1.0) 
// CGContextSetRGBStrokeColor(ctx, 0.6, 0.6, 0.6, 1.0); 
    // The same as 
// [[UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0] setStroke]; 
    // The same as 

// [[UIColor redColor] setStroke]; 

    // Draw concentric circles from the outside in 
    for (float currentRadius = maxRadius; currentRadius > 0; currentRadius -= 20) { 
     // Add a path to the context 
     CGContextAddArc(ctx, center.x, center.y, currentRadius, 0.0, M_PI * 2.0, YES); 

     [[self randomColor] setStroke]; 

     // Perform drawing instructions; removes path 
     CGContextStrokePath(ctx); 
    } 

回答

4

UIColor取0和1之間的浮動,作爲其RGB分量的值:

UIColor *colorToReturn = [[UIColor alloc] initWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha]; 
+1

哇,這很容易。謝謝! –

1

我使用下面的兩個宏來獲取隨機顏色。第一個是我經常在設置顏色時使用的簡單宏。第二個使用它返回隨機顏色:

#define _RGB(r,g,b,a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a] 
#define kCLR_RANDOM_COLOR _RGB(arc4random()%255, arc4random()%255, arc4random()%255, 1) 
相關問題