这里介绍一下iOS上最简单的两种类型,平移和旋转
这里使用UIKit中比较基本的API,由UIView的beginAnimations和commitAnimations来完成。
beginAnimations有两个参数,第一个参数是给这个动画设置一个名字,第二个参数可以是传递给animation的delegate使用的。
第一个例子,将一张图片从屏幕的右下角移动到左上角
- (void)startTopLeftImageViewAnimation { self.xcodeImageView2.frame = CGRectMake(self.view.bounds.size.width - 120, self.view.bounds.size.height - 90, 120, 90); self.xcodeImageView2.alpha = 1.0f; [UIView beginAnimations:kAnimationName2 context:(__bridge void * _Nullable)(self.xcodeImageView2)]; [UIView setAnimationDuration:3.0f]; [UIView setAnimationDelay:delay]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(imageViewDidStop:finished:context:)]; self.xcodeImageView2.frame = CGRectMake(0, 0, 120, 90); self.xcodeImageView2.alpha = 0.0f; [UIView commitAnimations];} - (void)imageViewDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { NSLog(@"Animation finished"); NSLog(@"Animation ID = %@", animationID); UIImageView *contextImageView = (__bridge UIImageView *)context; [contextImageView removeFromSuperview]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [self startBottomRightViewAnimationAfterDeley:2.0f]; }
这段代码中,在beginAnimations之后,设置了动画的时间为3秒钟完成所有动作,设置了delay值,在2秒后开始动画;动画完成了两个效果,第一个是从右下角移到了左上角,另一个是渐渐消失,注意在代码中设置了delegate,然后设置了didStopSelector,在相应的函数中,我们获取了UIImageView(通过beginAnimations第二个参数传入),然后将它从页面中删除。
我们再来看图片的旋转,旋转用到了affine的方法,即仿射变换,说白了也是一种平移,只不过是按照中心点进行旋转而已,代码如下
- (void)rotateAnimation { self.xcodeImageView.center = self.view.center; [UIView beginAnimations:@"clockwise" context:NULL]; [UIView setAnimationDuration:5.0f]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(clockwiseRotationStopped:finished:context:)]; self.xcodeImageView.transform = CGAffineTransformMakeRotation((90.0f * M_PI) / 180.0f); [UIView commitAnimations]; } - (void)clockwiseRotationStopped:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { [UIView beginAnimations:@"counterclockwise" context:NULL]; [UIView setAnimationDuration:5.0f]; self.xcodeImageView.transform = CGAffineTransformIdentity; [UIView commitAnimations]; }
代码的功能是先将图片顺时针旋转90度,结束后再回复到原状。当然在clockwiseRotationStopped中通过指定旋转角度来将图片回复到原状(transform使用CGAffineTransformIdentity),不过有个问题需要注意,transform的角度是个绝对值而不是相对值,所以在顺时针旋转后,要回复到原状,不能指定旋转角度为90,而是0才能让他回复到原状,像下面这样设置
- (void)clockwiseRotationStopped:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { [UIView beginAnimations:@"counterclockwise" context:NULL]; [UIView setAnimationDuration:5.0f]; self.xcodeImageView.transform = CGAffineTransformMakeRotation((0.0f * M_PI) / 180.0f); [UIView commitAnimations]; }
在此基础上可以有很多的应用,比如把平移和转动结合起来,用在一个圆形上面,就可以实现轮子滚动的效果
连同前两篇文章的示例代码可以在这里下载。