JasonBourne
JasonBourne

Reputation: 338

UIBezierPath Multiple Line Colors

My attempt to draw UIBezierPath lines with different colors is failing me. All the lines change to the currently selected color. All my path and information are all stored in an NSMutableArray called pathInfo. In path info I drop in array that contains the Path, Color, Width, and Type of line. This works fine except all the lines turn to whatever color the user has selected. I would appreciate any help greatly!

- (void)drawRect:(CGRect)rect {
    UIBezierPath *drawPath = [UIBezierPath bezierPath];
    drawPath.lineCapStyle = kCGLineCapRound;
    drawPath.miterLimit = 0;

    for (int i = 0; i < [pathInfo count]; i++){
        NSArray *row = [[NSArray alloc] initWithArray:[pathInfo objectAtIndex:i]];
        NSLog(@"Path: %@",[row objectAtIndex:0]);
        NSLog(@"Color: %@",[row objectAtIndex:1]);
        NSLog(@"Width: %@",[row objectAtIndex:2]);
        NSLog(@"Type: %@",[row objectAtIndex:3]);

        //width
        drawPath.lineWidth = [[row objectAtIndex:2] floatValue];

        //color
        [[row objectAtIndex:1] setStroke];

        //path
        [drawPath appendPath:[row objectAtIndex:0]];

    }

   UIBezierPath *path = [self pathForCurrentLine];
    if (path)
     [drawPath appendPath:path];

   [drawPath stroke];
}

- (UIBezierPath*)pathForCurrentLine {
    if (CGPointEqualToPoint(startPoint, CGPointZero) && CGPointEqualToPoint(endPoint, CGPointZero)){
        return nil;
    }

    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:startPoint];
    [path addLineToPoint:endPoint];

    return path;

}

Upvotes: 7

Views: 6177

Answers (2)

Rob
Rob

Reputation: 438287

Set your stroke color (and what have you), then stroke, and then move to the next path:

- (void)drawRect:(CGRect)rect
{
    for (int i = 0; i < [pathInfo count]; i++){
        NSArray *row = [[NSArray alloc] initWithArray:[pathInfo objectAtIndex:i]];

        NSLog(@"Path: %@",[row objectAtIndex:0]);
        NSLog(@"Color: %@",[row objectAtIndex:1]);
        NSLog(@"Width: %@",[row objectAtIndex:2]);
        NSLog(@"Type: %@",[row objectAtIndex:3]);

        UIBezierPath *path = [row objectAtIndex:0];

        path.lineCapStyle = kCGLineCapRound;
        path.miterLimit = 0;

        //width
        path.lineWidth = [[row objectAtIndex:2] floatValue];

        //color
        [[row objectAtIndex:1] setStroke];

        //path
        [path stroke];
    }

    UIBezierPath *path = [self pathForCurrentLine];
    if (path)
    {
        // set the width, color, etc, too, if you want
        [path stroke];
    }
}

Upvotes: 3

Lily Ballard
Lily Ballard

Reputation: 185841

The stroke/fill colors only affect the -stroke command. They don't affect the -appendPath: command. Paths don't contain per-segment color information.

If you need a multi-colored line you're going to need to stroke each color separately.

Upvotes: 3

Related Questions