如何通过在一定时间后更改图像来创建动画

时间:2013-07-11 11:13:25

标签: ios animation

大家好我是xcode的新手,我试图通过更改图像来触摸气球:这是我的代码: 现在我面临的问题是它没有动画图像意味着动画计时器不工作:请指导我应该怎样做以及时间动画图像:如果我没有正确做到那么请指导我,我该怎么做作者:NSTimer?

-(void)baloonbursting:(UIButton *)button withEvent:(UIEvent *)event{
if ([[UIImage imageNamed:@"redbaloons.png"] isEqual:button.currentImage]) {
    NSLog(@"em redbaloons.png");
    UIImage *bubbleImage3 = [UIImage imageNamed:@"redburst.png"];
    [button setImage:bubbleImage3 forState:UIControlStateNormal];
}
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView animateWithDuration:1.0f animations:^(){
    // define animation
    if ([[UIImage imageNamed:@"redburst.png"] isEqual:button.currentImage]) {
        NSLog(@"em redbaloons.png");
        UIImage *bubbleImage3 = [UIImage imageNamed:@"redburst2.png"];
        [button setImage:bubbleImage3 forState:UIControlStateNormal];
    }   
}
 completion:^(BOOL finished){
 // after the animation is completed call showAnimation again
[UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionCurveEaseOut|UIViewAnimationOptionAllowUserInteraction animations:^{

                     } completion:^(BOOL finished){
                         if (finished) {
                             [button removeFromSuperview];
                         }}];
                 }];

}

1 个答案:

答案 0 :(得分:2)

我希望你能给你一个解决方案,向你展示正确的思考方向。也就是说,为什么我在Xcode中开发了一个小型测试项目,并且我控制了这段代码真的有效。

首先:忘记这个动画的NSTimers!

这个想法是,您可以“玩”子视图,因为您可以将其alpha属性从0.0(不可见)更改为1.0(完全不透明),这些属性由SDK的视图动画支持。

请根据您自己的文件名更改图像名称(我在这里使用过自己的文件名)。

以下方法检查按钮的图像是否应该调用动画 - 正是您之前所做的。如果满足此条件,则会在视觉上将按钮图像的更改设置为另一个图像:

- (IBAction)balloonBursting:(UIButton *)sender
{
    BOOL doAnimate = NO;

    UIImageView *ivOldBubbleImage;
    UIImageView *ivNewBubbleImage;

    if ([[UIImage imageNamed:@"BalloonYellow.png"] isEqual:sender.currentImage]) {
        NSLog(@"will animate");
        doAnimate = YES;

        UIImage *newImage = [UIImage imageNamed:@"BalloonPurple.png"];
        ivNewBubbleImage = [[UIImageView alloc] initWithImage:newImage];
        ivNewBubbleImage.alpha = 0.0;
        ivOldBubbleImage = sender.imageView;
        [sender addSubview:ivNewBubbleImage];
    }

    if (doAnimate) {
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView animateWithDuration:1.0f animations:^(){
            // define animation
            ivOldBubbleImage.alpha = 0.0;
            ivNewBubbleImage.alpha = 1.0;
        }
                         completion:^(BOOL finished){
                             [sender setImage:ivNewBubbleImage.image forState:UIControlStateNormal];
                             [ivNewBubbleImage removeFromSuperview];
                         }];
    }
}