ios平移与抖动动画的简单实现

废话不多说,直接上代码:

首先在.h中声明如下参数:

    float       imageWidth;//图片宽度
    UIImageView *moveView;
    UIButton    *button;
    int         touchNumber;//点击次数

在.m中创建视图:

    self.view.backgroundColor = [UIColor whiteColor];
    //创建imageview
    UIImage *image = [UIImage imageNamed:@"photo.jpg"];
    imageWidth = image.size.width;
    moveView = [[UIImageView alloc] initWithFrame:CGRectMake(-imageWidth, 200, imageWidth, image.size.height)];
    moveView.image = image;
    moveView.backgroundColor = [UIColor redColor];
    [self.view addSubview:moveView];
    
    //创建按钮
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(100, 100, 100, 30);
    [button setTitle:@"Touch me" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(doSomething) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    touchNumber = 1;//默认为1;

按钮点击事件:

/*
 *第一次点击按钮,图片从左侧平移过来
 *touchNumber自加1
 *再次点击,imageview只执行抖动动画
 */
- (void) doSomething
{
    if (touchNumber == 1) {
        //添加平移动画,
        [UIView animateWithDuration:0.5 animations:^{
            moveView.center = CGPointMake(moveView.center.x + imageWidth/2 + [UIScreen mainScreen].bounds.size.width/2, moveView.center.y);
        } completion:^(BOOL finished) {
            //平移结束添加抖动动画
            [self shakeAnimation];
        }];
        
    }
    else{
        [self shakeAnimation];
    }
    ++ touchNumber;
}

抖动动画:

- (void) shakeAnimation
{
    CABasicAnimation* shake = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    //设置抖动幅度
    shake.fromValue = [NSNumber numberWithFloat:+0.1];
    shake.toValue = [NSNumber numberWithFloat:-0.1];
    shake.duration = 0.1;
    shake.autoreverses = YES; //是否重复
    shake.repeatCount = 4;
    [moveView.layer addAnimation:shake forKey:@"imageView"];
    moveView.alpha = 1.0;
    [UIView animateWithDuration:2.0
                          delay:2.0
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:nil completion:nil];

}

动画效果:



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值