iOS drawRect 时如何设置不同的描边颜色
how to set diffrent strokecolor when drawRect in iOS
我想用'drawRect:'方法绘制不同的笔触颜色。这是我的代码:
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
。不知道为什么。
当您调用 CGContextStrokePath
时,它会使用最后设置的笔触颜色。给定路径只能用单一颜色描边(忽略渐变)。
您无法像您尝试的那样设置每段路径的颜色。
如果您希望路径的不同部分具有不同的颜色,那么您需要创建多条路径,每种颜色至少创建一条路径。
因为只有两种颜色,所以可以创建两条路径。将线段添加到适当的路径。然后在最后,添加并描边两条路径中的每一条,在描边之前设置它的颜色。
我想用'drawRect:'方法绘制不同的笔触颜色。这是我的代码:
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
。不知道为什么。
当您调用 CGContextStrokePath
时,它会使用最后设置的笔触颜色。给定路径只能用单一颜色描边(忽略渐变)。
您无法像您尝试的那样设置每段路径的颜色。
如果您希望路径的不同部分具有不同的颜色,那么您需要创建多条路径,每种颜色至少创建一条路径。
因为只有两种颜色,所以可以创建两条路径。将线段添加到适当的路径。然后在最后,添加并描边两条路径中的每一条,在描边之前设置它的颜色。