如何为每种颜色创建具有不同值的多色进度视图

时间:2021-04-01 09:06:23

标签: ios swift progress-bar uiprogressview

关于如何创建具有 3 种不同颜色的进度条并根据服务器提供的值显示进度,我尝试了不同的方法和其他资源,但我找不到任何东西。我如何创建一个像下面这样的进度条。我想根据我可以从后端获得的值来显示进度,这些值可以为不同的用户改变。这是示例json。绿色 -> “赢了”,红色 -> “失败”和深灰色 -> “未定”

"condition": {
          "won": 2,
          "lost": 3,
          "undecided": 0
        }

enter image description here

2 个答案:

答案 0 :(得分:0)


- (void)setCurrentProgressWithIndex1:(float)index1 index2:(float)index2 index3:(float)index3 {
    _index1 = index1;
    _index2 = index2;
    _index3 = index3;
    
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [self drawProgressWithContext:ctx];
}

- (void)drawProgressWithContext:(CGContextRef)ctx {
    float width = self.frame.size.width;
    //  index
    float start_index = 0.0f;
    if (_index1 != 0.0f) {
        UIBezierPath* bezierPath = UIBezierPath.bezierPath;
        bezierPath.lineCapStyle = kCGLineCapRound;
        bezierPath.lineJoinStyle = kCGLineJoinBevel;
        [bezierPath moveToPoint: CGPointMake(start_index, 0)];
        [bezierPath addLineToPoint: CGPointMake(start_index, 20)];
        [bezierPath addLineToPoint: CGPointMake(start_index + width * _index1, 20)];
        [bezierPath addLineToPoint: CGPointMake(start_index + width * _index1, 0)];
        [UIColor.redColor setFill];
        [bezierPath fill];
        start_index += width * _index1;
    }
    
    if (_index2 != 0.0f) {
        UIBezierPath* bezierPath = UIBezierPath.bezierPath;
        bezierPath.lineCapStyle = kCGLineCapRound;
        bezierPath.lineJoinStyle = kCGLineJoinBevel;
        [bezierPath moveToPoint: CGPointMake(start_index, 0)];
        [bezierPath addLineToPoint: CGPointMake(start_index, 20)];
        [bezierPath addLineToPoint: CGPointMake(start_index + width * _index2, 20)];
        [bezierPath addLineToPoint: CGPointMake(start_index + width * _index2, 0)];
        [UIColor.greenColor setFill];
        [bezierPath fill];
        start_index += width * _index2;
    }

    if (_index3 != 0.0f) {
        UIBezierPath* bezierPath = UIBezierPath.bezierPath;
        bezierPath.lineCapStyle = kCGLineCapRound;
        bezierPath.lineJoinStyle = kCGLineJoinBevel;
        [bezierPath moveToPoint: CGPointMake(start_index, 0)];
        [bezierPath addLineToPoint: CGPointMake(start_index, 20)];
        [bezierPath addLineToPoint: CGPointMake(start_index + width * _index3, 20)];
        [bezierPath addLineToPoint: CGPointMake(start_index + width * _index3, 0)];
        [UIColor.blueColor setFillx];
        [bezierPath fill];
    }
}

答案 1 :(得分:-1)