抖动特效 shaking animation

本文介绍了两种在iOS中实现视图震动效果的方法:一种是通过设置动画代理和选择器来实现视图的左右震动;另一种是使用块语法简化震动效果的实现过程。这两种方法都能够让应用程序中的视图产生地震般的震动效果。

- (void)earthquake:(UIView*)itemView

{

// AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

CGFloat t = 2.0;

CGAffineTransform leftQuake =CGAffineTransformTranslate(CGAffineTransformIdentity, t, -t);

CGAffineTransform rightQuake =CGAffineTransformTranslate(CGAffineTransformIdentity, -t, t);

itemView.transform = leftQuake; // starting point

[UIView beginAnimations:@"earthquake"context:itemView];

[UIView setAnimationRepeatAutoreverses:YES];// important

[UIView setAnimationRepeatCount:3];

[UIView setAnimationDuration:0.05];

[UIView setAnimationDelegate:self];

[UIView setAnimationDidStopSelector:@selector(earthquakeEnded:finished:context:)];

itemView.transform = rightQuake; // end here & auto-reverse

[UIView commitAnimations];

}


- (void)earthquakeEnded:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context

{

if ([finished boolValue])

{

UIView* item = (UIView *)context;

//每次变换前都要置位,不然你变换用的坐标系统不是屏幕坐标系统(即绝对坐标系统),而是上一次变换后的坐标系统

item.transform = CGAffineTransformIdentity;

}

}



方法二 利用块语法


- (void)shakeView:(UIView *)viewToShake
{
  CGFloat t = 2.0;
  CGAffineTransform translateRight = CGAffineTransformTranslate(CGAffineTransformIdentity, t, 0.0);
  CGAffineTransform translateLeft = CGAffineTransformTranslate(CGAffineTransformIdentity, -t, 0.0);

  viewToShake.transform = translateLeft;

  [UIView animateWithDuration:0.07 delay:0.0 options:UIViewAnimationOptionAutoreverse|UIViewAnimationOptionRepeat animations:^{
    [UIView setAnimationRepeatCount:2.0];
    viewToShake.transform = translateRight;
  } completion:^(BOOL finished) {
    if (finished) {
      [UIView animateWithDuration:0.05 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
        viewToShake.transform = CGAffineTransformIdentity;
      } completion:NULL];
    }
  }];

}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值