UIBezierPath 多色线条

7

我试图使用不同颜色绘制UIBezierPath线条,但是失败了。所有的线都会变成当前所选颜色。我的路径和信息都存储在一个名为pathInfo的NSMutableArray中。在pathInfo中,我放置了一个包含路径、颜色、宽度和线条类型的数组。这个方法很好用,只是所有的线都变成了用户选择的颜色。非常感谢任何帮助!

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

}

如果可能的话,请把你完整的代码给我。实际上,我也遇到了同样的问题。但是我在使用touchesBegan、touchesMoved和touchesEnd方法。可是我还是做不到。 - Abha
2个回答

3

设置描边颜色(等等),然后使用stroke命令,接着移动到下一个路径:

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

1
哇,你的答案也是正确的!我也很感谢你的帮助,Rob!这种方法似乎更有效。 - JasonBourne

3
描边/填充颜色只会影响到-stroke命令,不会影响到-appendPath:命令。路径本身不包含每个线段的颜色信息。
如果需要多色线条,需要分别对每个颜色进行描边。

1
那么我该怎么做呢,@Kevin-Ballard? - JasonBourne
这不就是我正在做的吗?每个都在for语句中绘制。@kevin-ballard - JasonBourne
1
@JasonBourne:我不知道你的“-pathForCurrentLine”方法中有什么内容,但是在for循环内部,你应该用“[[row objectAtIndex:0] stroke]”代替“[drawPath appendPath:[row objectAtIndex:0]]”。 - Lily Ballard
@Kevin-Ballad 谢谢!你刚刚防止了我变秃! - JasonBourne
原来是这样。我只需要滚动一下就好了。无论如何,在设置好你想要的描边颜色后,你应该直接在 -drawRect: 中绘制路径。 - Lily Ballard
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接