Reputation: 11
I have been searching the web for a library\solution how to achieve this. I need to make a circular progress bar. The progress bar should be built from up to 3 colors, depending of the progress value. I have found several circular progress bars but I'm having trouble modifying them to the required result.
It's supposed to look sort of like the following image, only with a value label in the centre.
When setting the progress, it should animate to that point. Each color is up to a certain progress and then it should change with gradient to the next one.
Any ideas on how to achieve this?
Upvotes: 0
Views: 2419
Reputation: 8014
I use a progress HUD from github here. It has an annular progress display.
I used the drawing code from this and had a play making a few adjustments. The following code will draw you an annular ring with each part of the ring using a color based on the progress. Code assumes the progress is in self.progress
.
This code draws an annular ring in steps of 0.05 progress. So that gives you 20 color changes possible. Reduce this to show more and increase to show less. This code changes the ring color from red at 0.0 progress to green at 1.0 progress as a demonstration. Just change the code which sets the color to an algorithm of your choosing, table lookup etc...
It works when I do the changes inside the HUD linked to above. Just put this function in the view you want to draw the annular ring in.
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat lineWidth = 5.f;
CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
CGFloat radius = (self.bounds.size.width - lineWidth)/2;
CGFloat startAngle = - ((float)M_PI / 2); // 90 degrees
CGFloat endAngle = (2 * (float)M_PI) + startAngle;
UIBezierPath *processPath = [UIBezierPath bezierPath];
processPath.lineCapStyle = kCGLineCapRound;
processPath.lineWidth = lineWidth;
endAngle = (self.progress * 2 * (float)M_PI) + startAngle;
CGFloat tmpStartAngle=startAngle;
CGFloat shownProgressStep=0.05; // The size of progress steps to take when rendering progress colors.
for (CGFloat shownProgress=0.0;shownProgress <= self.progress ;shownProgress+=shownProgressStep){
endAngle=(shownProgress * 2 *(float)M_PI) + startAngle;
CGFloat rval=shownProgress;
CGFloat gval=(1.0-shownProgress);
UIColor *progressColor=[UIColor colorWithRed:rval green:gval blue:0.0 alpha:1.0];
[progressColor set];
[processPath addArcWithCenter:center radius:radius startAngle:tmpStartAngle endAngle:endAngle clockwise:YES];
[processPath stroke];
[processPath removeAllPoints];
tmpStartAngle=endAngle;
}
}
Upvotes: 1
Reputation: 159
Most probably you will have to go all the way down to CoreGraphics. You can find some instructions on how to that here:
Draw segments from a circle or donut
Upvotes: 0