简体   繁体   English

在iOS中使用drawRect时如何设置不同的笔触颜色

[英]how to set diffrent strokecolor when drawRect in iOS

在此处输入图片说明

I want to draw diffrent strokecolor in 'drawRect:' method. 我想在'drawRect:'方法中绘制不同的strokecolor。 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 . 所有行都是kHomeSleepCellProgressColor I don't know why. 我不知道为什么

When you call CGContextStrokePath , it uses whatever stroke color has been set last. 调用CGContextStrokePath ,它将使用最后设置的任何笔触颜色。 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. 然后在最后,分别添加和描画两条路径,并在描边之前设置其颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM