如何制作“shaking”动画

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (75)

在我的xcode项目中,我有一个UIImage。我想让它从左向右摇晃(动画)一点点。我写了这个代码,但是,它不工作。

-(void)errorShake
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1.0];



    [lockImage setTransform:CGAffineTransformMakeRotation(-5 * M_PI / 180.0)];
    [lockImage setTransform:CGAffineTransformMakeRotation(-10 * M_PI / 180.0)];
    [lockImage setTransform:CGAffineTransformMakeRotation(-15 * M_PI / 180.0)];
    [lockImage setTransform:CGAffineTransformMakeRotation(-20 * M_PI / 180.0)];
     [lockImage setTransform:CGAffineTransformMakeRotation(-15 * M_PI / 180.0)];
     [lockImage setTransform:CGAffineTransformMakeRotation(-10 * M_PI / 180.0)];
     [lockImage setTransform:CGAffineTransformMakeRotation(-5 * M_PI / 180.0)];
     [lockImage setTransform:CGAffineTransformMakeRotation(0 * M_PI / 180.0)];
     [lockImage setTransform:CGAffineTransformMakeRotation(5 * M_PI / 180.0)];
     [lockImage setTransform:CGAffineTransformMakeRotation(10 * M_PI / 180.0)];
     [lockImage setTransform:CGAffineTransformMakeRotation(15 * M_PI / 180.0)];
     [lockImage setTransform:CGAffineTransformMakeRotation(20 * M_PI / 180.0)];
     [lockImage setTransform:CGAffineTransformMakeRotation(15 * M_PI / 180.0)];
     [lockImage setTransform:CGAffineTransformMakeRotation(10 * M_PI / 180.0)];
     [lockImage setTransform:CGAffineTransformMakeRotation(5 * M_PI / 180.0)];
     [lockImage setTransform:CGAffineTransformMakeRotation(0 * M_PI / 180.0)];


    [UIView commitAnimations];
}

你能告诉我,我怎么能让我的image shaking?

提问于
用户回答回答于

这是我使用的代码。

 -(void)shakeView {

        CABasicAnimation *shake = [CABasicAnimation animationWithKeyPath:@"position"];
        [shake setDuration:0.1];
        [shake setRepeatCount:2];
        [shake setAutoreverses:YES];
        [shake setFromValue:[NSValue valueWithCGPoint:
                                 CGPointMake(lockImage.center.x - 5,lockImage.center.y)]];
        [shake setToValue:[NSValue valueWithCGPoint:
                               CGPointMake(lockImage.center.x + 5, lockImage.center.y)]];
        [lockImage.layer addAnimation:shake forKey:@"position"];
    }

作为Jere提及。确保包含导入:

#import <QuartzCore/QuartzCore.h>

您也可以将其添加为类别UIView

用户回答回答于

brynbodayles的答案也适用于iOS8下的swift动画动画。

随着QuartzCore的导入:

func shakeView(){
    var shake:CABasicAnimation = CABasicAnimation(keyPath: "position")
    shake.duration = 0.1
    shake.repeatCount = 2
    shake.autoreverses = true

    var from_point:CGPoint = CGPointMake(LoginField.center.x - 5, LoginField.center.y)
    var from_value:NSValue = NSValue(CGPoint: from_point)

    var to_point:CGPoint = CGPointMake(LoginField.center.x + 5, LoginField.center.y)
    var to_value:NSValue = NSValue(CGPoint: to_point)

    shake.fromValue = from_value
    shake.toValue = to_value
    LoginField.layer.addAnimation(shake, forKey: "position")
}

扫码关注云+社区

领取腾讯云代金券