ko1984
ko1984

Reputation: 41

how to give a CGPoint line unique colors Xcode

A very simple XCode iPhone app. Blank screen, draw lines, each line is to have a unique colour given via a random number gen. I have the code to give me random colours, but I cannot get the lines to retain the colour individually. Any time the screen is drawn, the colour changes for all lines in my array.

here is the code to set the color to each line:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{    
    for (UITouch *t in touches) {
    // Is this a double-tap?
        if ([t tapCount] > 1) {
            [self clearAll];
            return;
    }

    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

    Colour=[UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];        

    // Use the touch object (packed in an NSValue) as the key
    NSValue *key = [NSValue valueWithPointer:t];

    // Create a line for the value
    CGPoint loc = [t locationInView:self];
    Line *newLine = [[Line alloc] init]; 
    [newLine setBegin:loc];
    [newLine setEnd:loc];
    [newLine setCOLOUR:Colour];

    // Put pair in dictionary
    [linesInProcess setObject:newLine forKey:key];
    [newLine release];
}
}

here is the code I've been using to draw lines.

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 10.0);
    CGContextSetLineCap(context, kCGLineCapRound);

    for (Line *line in completeLines) {
        [Colour set];
        CGContextMoveToPoint(context, [line begin].x, [line begin].y);
        CGContextAddLineToPoint(context, [line end].x, [line end].y);
        CGContextStrokePath(context);
    }

    // Draw lines in process in red
    [[UIColor redColor] set];
    for (NSValue *v in linesInProcess) {
        Line *line = [linesInProcess objectForKey:v];
        CGContextMoveToPoint(context, [line begin].x, [line begin].y);
        CGContextAddLineToPoint(context, [line end].x, [line end].y);
        CGContextStrokePath(context);
    }
}

To reiterate: I'm trying to give each line drawn on the interface a unique colour. Said colour is given by the random num gen.

Appreciate the help, people. :D

Upvotes: 3

Views: 667

Answers (1)

Mundi
Mundi

Reputation: 80265

In your drawRect in the loop through linesInProcess you are not setting the color. You need to use the color information in your line object and reset the color in each loop iteration:

CGContextSetStrokeColorWithColor(context, line.COLOUR.CGColor);

or, alternatively

[line.COLOUR set];

The same applies to your completeLines loop.

PS: You would do yourself a favor by using the usual camel case variable names for your classes' properties.

Upvotes: 2

Related Questions