Search code examples
iosobjective-ccore-graphics

how to set diffrent strokecolor when drawRect in iOS


enter image description here

I want to draw diffrent strokecolor in 'drawRect:' method. Here is my code:

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

But it does not work. All of the lines are kHomeSleepCellProgressColor. I don't know why.


Solution

  • When you call CGContextStrokePath, it uses whatever stroke color has been set last. A given path can only be stroked with a single color (ignoring gradients).

    You can't set the color of each segment of a path like you are attempting.

    If you want different parts of the path to have different colors then you need to create multiple paths, at least one for each color you need.

    Since you only have two colors, you can create two paths. Add the line segment to the appropriate path. Then at the end, add and stroke each of the two paths, setting its color just before stroking it.