如何在iOS中的drawRect中设置不同的strokecolor

时间:2017-07-13 02:20:23

标签: ios objective-c core-graphics

enter image description here

我想在'drawRect:'方法中绘制不同的strokecolor。这是我的代码:

CGPoint center = CGPointMake(rect.size.width * 0.5, rect.size.height * 0.5);
CGFloat radius = rect.size.width * 0.5;
UIBezierPath *path = [UIBezierPath bezierPath];
path.lineCapStyle = kCGLineCapRound;
path.lineJoinStyle = kCGLineJoinRound;
CGContextRef ctx = UIGraphicsGetCurrentContext();
[kHomeSleepCellTrackColor set];
for (int i = 0; i < self.textArray.count*4; i++) {
    CGFloat angle = i / 48.0 * M_PI * 2; //48.0为总份数
    // 圆上的点  转换成iOS坐标
    CGFloat x = center.x + radius * cos(angle);
    CGFloat y = center.y + radius * sin(angle);
    CGFloat x0 = center.x + (radius - 1) * cos(angle);
    CGFloat y0 = center.y + (radius - 1) * sin(angle);

    [path moveToPoint:CGPointMake(x, y)];
    // 4的倍数就不画
    if (i % 4 == 0) {
        [path addLineToPoint:CGPointMake(x, y)];
    } else {
        [path addLineToPoint:CGPointMake(x0, y0)];
    }
    //刷新时要设置不同颜色
    if (i<24) {
        [kHomeSleepCellTrackColor set];
    } else {
        [kHomeSleepCellProgressColor set];
    }
}
CGContextAddPath(ctx, path.CGPath);
CGContextStrokePath(ctx);

但它不起作用。所有行都是kHomeSleepCellProgressColor。我不知道为什么。

1 个答案:

答案 0 :(得分:0)

当您致电CGContextStrokePath时,它会使用最后设置的任何笔触颜色。给定路径只能使用单一颜色(忽略渐变)进行描边。

您无法像尝试一样设置路径的每个段的颜色。

如果您希望路径的不同部分具有不同的颜色,则需要创建多个路径,至少一个路径用于您需要的每种颜色。

由于您只有两种颜色,因此可以创建两个路径。将线段添加到适当的路径。然后在最后,添加并描绘两个路径中的每一个,在触摸它之前设置其颜色。