iOS中的动画条形图

2uluyalo  于 2023-06-25  发布在  iOS
关注(0)|答案(1)|浏览(151)

我画了一个条形图,它的工作正常,除了它没有动画。例如:填充颜色0- 50%。我使用简单的DrawRect方法来绘制。下面是我的代码:

- (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);

}

有没有简单的方法添加动画?

mklgxw1f

mklgxw1f1#

我相信你想让条形图的高度动画化。我建议您将每个栏实现为一个单独的UIview,一个简单的矩形。您也可以使用自定义绘图将它们全部放置在一个视图中。然后,您需要缩放这些视图或在动画块内更改其帧,方法如下:

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

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

一个伟大的教程见this
这是一个例子,如果你没有很多时间。

[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!");
                 }];

相关问题