2012-10-01 6 views
1

Je veux changer la couleur de fond de ma fenêtre chaque seconde alors voici mon code:changer la couleur de fond de la fenêtre

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{ 
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(newColor) userInfo:nil repeats:YES]; 
} 

-(void)newColor { 
    int r; 
    r = (arc4random()%250)+1; 
    NSLog(@"%i", r); 

    int g; 
    g = (arc4random()%250)+1; 
    NSLog(@"%i", g); 

    int b; 
    b = (arc4random()%250)+1; 
    NSLog(@"%i", b); 

    NSColor *theColor = [NSColor colorWithDeviceRed:(int)r green:(int)g blue:(int)b alpha:(float)1.0]; 
    [_window setBackgroundColor:theColor]; 
} 

Je pense que mon problème est dans la définition des couleurs avec les variables, mais je ne suis pas sûr.

+0

Ainsi, ont l'une des réponses ci-dessous vous a aidé? –

Répondre

0

je vous recommande d'effectuer les modifications suivantes ..

#define ARC4RANDOM_MAX  0x100000000 

-(void)newColor:(NSTimer *)sender { 
//Give your void an NSTimer argument so you have to ability to invalidate the timer if you ever want to. 
    float r = ((float)arc4random()/ARC4RANDOM_MAX); 
    float g = ((float)arc4random()/ARC4RANDOM_MAX); 
    float b = ((float)arc4random()/ARC4RANDOM_MAX); 

//These will generate random floats between zero and one. NSColor wants floats between zero and one, not ints between 0-255. 


    NSLog(@"R: %f | G: %f | B: %f",r,g,b); 


    if (r >= 0.5 && g >= 0.5 && b >= 0.5) { 
     [sender invalidate]; 
    } 
//Example of invalidating sender 


    NSColor *theColor = [NSColor colorWithDeviceRed:r green:g blue:b alpha:1.0f]; 
    [_window setBackgroundColor:theColor]; 
} 
0

il suffit de changer votre méthode newColor comme ci-dessous

-(void)newColor 
{ 
    int r; 
    r = (arc4random()%250)+1; 
    NSLog(@"%i", r); 

    int g; 
    g = (arc4random()%250)+1; 
    NSLog(@"%i", g); 

    int b; 
    b = (arc4random()%250)+1; 
    NSLog(@"%i", b); 

    float red = (float)r/255; 
    float blue = (float)b/255; 
    float green = (float)g/255; 

    NSLog(@"red-%f, blue-%f, green-%f",red, blue, green); 
    NSColor *theColor = [NSColor colorWithDeviceRed green:green blue:blue alpha:1.0]; 
    [_window setBackgroundColor:theColor]; 
} 
Questions connexes