Search code examples
ioscore-graphics

Animated bar graph in iOS


I am drawing a bar chart, it works fine except it doesn't have animation. Ex: fill color 0-50%. I am using simple DrawRect method to draw. Here is my code:

- (void)drawRect:(CGRect)rect
{
    CGFloat height = self.bounds.size.height;
CGContextRef context = UIGraphicsGetCurrentContext();
// CGContextClearRect(context, rect);
CGContextSetFillColorWithColor(context, [self colorWithR:149 G:21 B:29 A:1].CGColor);

CGFloat barWidth = 52;
int count = 0;
NSNumber *num = [NSNumber numberWithFloat:graphValue];

CGFloat x = count * (barWidth + 10);
CGRect barRect = CGRectMake(x, height - ([num floatValue] * height), barWidth, [num floatValue] * height);
CGContextAddRect(context, barRect);
count++;

CGContextFillPath(context);

}

Is there a simple way to add animation?


Solution

  • I believe you want to animate the heights of the bars in the bargraph. I suggest you implement each bar as a separate UIview, a simple rectangle. You can also put all of them in one view with a custom drawRect. Then you need to scale these views or change their frame inside the animation block of either of the following methods:

    + (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion
    

    OR

    + (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations
    

    For a great tutorial see this.

    This is an example if you don't have a lot of time.

    [UIView animateWithDuration:1//Amount of time the animation takes.
                          delay:0//Amount of time after which animation starts.
                        options: UIViewAnimationCurveEaseOut//How the animation will behave.
                     animations:^{
                        //here you can either set a CGAffineTransform, or change your view's frame.
                        //Both will work just fine.
                        yourBarView.transform = CGAffineTransformMakeScale (
                        scaleForX,//say 1, you dont want it to change.
                        scaleForY//say 20, you want to make it 20 times larger in the y                                               
                        //direction.
                        //Note* to animate from a zero height to a finite height change the                  
                        //view's frame.
                        //yourBarView.frame = CGRectMake(0,0,20,100);
                        );
                     }
                     completion:^(BOOL finished){//This block is called when the animation completes.
                         NSLog(@"Done!");
                     }];