您的位置:首页 > 移动开发 > IOS开发

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

2015-11-03 15:38 495 查看
废话不多说,直接上代码:

首先在.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];

}


动画效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: