【问题标题】:Overlapping animations help?重叠动画有帮助吗?
【发布时间】:2009-09-26 20:32:40
【问题描述】:

这是我的代码,用于让蝙蝠拍打翅膀并响应触摸。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSArray * imageArray = [[NSArray alloc] initWithObjects:
                            [UIImage imageNamed:@"Bat1.png"],
                            [UIImage imageNamed:@"Bat2.png"],
                            [UIImage imageNamed:@"Bat3.png"],
                            [UIImage imageNamed:@"Bat2.png"],
                            [UIImage imageNamed:@"Bat1.png"],
                            [UIImage imageNamed:@"Bat4.png"], 
                            [UIImage imageNamed:@"Bat5.png"],
                            [UIImage imageNamed:@"Bat6.png"],
                            [UIImage imageNamed:@"Bat5.png"],
                            [UIImage imageNamed:@"Bat4.png"],
                            nil];

    UIImageView * batView = [[UIImageView alloc] initWithFrame:
                             CGRectMake(0, 0, 80, 56)];
    batView.animationImages = imageArray;
    batView.animationDuration = 0.70;
    [follower1 addSubview:batView];
    [batView startAnimating];
    [UIImageView beginAnimations:@"follow" context:nil];
    [UIImageView setAnimationDuration:1];
    [UIImageView setAnimationBeginsFromCurrentState:YES];
    UITouch *touch = [touches anyObject];
    follower1.center = [touch locationInView:self];
    [UIImageView commitAnimations];
    [batView release]; 
}

问题在于,在第二次触摸后,动画会相互重叠,所以每次触摸后看起来下面都有很多蝙蝠!

【问题讨论】:

    标签: iphone cocoa-touch animation uiimageview


    【解决方案1】:

    发生这种情况是因为每次触摸开始时您都会添加一个新的batView

    解决此问题的一种方法是添加一次batView,例如在超级视图或视图控制器的init 方法中。如果您只想在触摸发生时出现batView,您可以通过以下方式将其隐藏:

    // during initialization
    batView.hidden = YES;
    

    由于您每次总是做相同的动画,您不妨同时设置动画参数,而不是每次触摸都重复相同的设置:

    // still during initialization
    NSArray* imageArray = /* set up your image array */;
    batView.animationImages = imageArray;
    batView.animationDuration = 0.7;
    

    现在,当触摸发生时,您可以通过启动动画来处理它:

    // Within touchesBegan:
        ...
        // Start the batView animation.
        batView.hidden = NO;
        if (![batView isAnimating]) [batView startAnimating];
        // Hide the animation when it's done.
        [self performSelector:@selector(hideBat) withObject:nil afterDelay:0.71];
    }
    
    // Later:
    
    - (void) hideBat { batView.hidden = YES; }
    

    如果您不总是希望它在单个动画后立即消失,您可能希望在 hideBat 中做一些不同的事情。例如,如果您希望始终重复动画直到用户停止点击,您可以设置一个 NSTimer 对象,使其在至少 0.7 秒内没有用户触摸时立即关闭。每次用户再次触摸屏幕时,您都可以重置此计时器。

    参考:UIImageView docs,其中包含动画方法的简要说明。

    【讨论】:

      猜你喜欢
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      • 2011-03-14
      • 2011-08-28
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多