UIKit封装的系统动画

时间:2023-03-09 06:20:41
UIKit封装的系统动画

简介

在UIKit中,对UIView封装了很多类方法来进行简单的动画实现,在动画过程中,通过对属性值的修改来完成一系列的效果。
在IOS4以前,主要通过
+ beginAnimation
+ setAnimationDuration:设置动画时长
+ setAnimationDelay:设置延迟时间
+ setAnimationDelegate:设置代理

code..... 写入一些属性改变例如仿射变换,透明度等

+ commitAnimation

代理可以监听一些事件,比如动画结束后,可以调用代理方法进行一系列处理。

在IOS4以后,伴随着Block语法,有了更好的方法
+ animateWithDuration:delay:options:animations:completion:

前两个属性前面见过,第三个属性主要设置动画的速度效果,比如渐入渐出(EaseInOut),匀速(Linear)等
animations后面是一个块语法,设置动画的相关效果。
completion后面也是一个块语法,设置动画完成后执行的代码。

简单的位移动画


- (void)translateAnimation
{
[UIView animateWithDuration:1
delay:1
options:UIViewAnimationOptionCurveEaseInOut
animations:^{
_imageView.center = CGPointMake(270, 410);
} completion:^(BOOL finished) {
NSLog(@"done");
}];
}

这个方法实现了通过设置属性的位移动画


我们还可以通过这个类方法对透明度,大小等等几乎所有属性进行改变增加动画效果

增加仿射变换


- (void)transformAnimation
{
[UIView animateWithDuration:3
delay:1
options:UIViewAnimationOptionCurveEaseIn
animations:^{
_imageView.center = CGPointMake(270, 410);
_imageView.transform = CGAffineTransformRotate(CGAffineTransformScale(_imageView.transform, 0.6, 0.6), M_PI);
_imageView.alpha = 0.0;
} completion:^(BOOL finished) {
NSLog(@"done");
}];
}

在这个方法中,对UIImageView的transform属性设置进行了嵌套,在旋转180度的同时进行了缩放。由于设置了alpha,所以也还有一个渐渐消失的效果。

一般来说,如果通过设置alpha为0后,需要从父视图中remove掉这个对象。

利用completion设置连续动画


- (void)transformAnimation
{
[UIView animateWithDuration:3
delay:1
options:UIViewAnimationOptionCurveEaseIn
animations:^{
_imageView.center = CGPointMake(270, 410);
_imageView.transform = CGAffineTransformRotate(CGAffineTransformScale(_imageView.transform, 0.6, 0.6), M_PI);
_imageView.alpha = 0.0;
} completion:^(BOOL finished) {
NSLog(@"done");
[UIView animateWithDuration:3
delay:0
options:UIViewAnimationOptionCurveEaseIn
animations:^{
_imageView.center = CGPointMake(50, 50);
_imageView.transform = CGAffineTransformIdentity;
_imageView.alpha = 1.0;
} completion:nil];
}];
}
我们在上个方法的基础上进行了修改,在completion中又加入了一个动画效果,使这个图片恢复到最初的状态。
这里面CGAffineTransformIdentity为单位矩阵,是他的transform属性回复到原貌。

利用NSTimer完成连续动画


我们也可以使用定时器来完成连续动画效果

先增加两个私有成员,并且可以根据调试效果来设置_step初值

@interface ViewController ()
{
NSTimer *_timer;
NSInteger _step;
}

然后是方法


- (void)timerAnimation
{
_timer = [NSTimer scheduledTimerWithTimeInterval:0.05
target:self
selector:@selector(animateWithTimer)
userInfo:nil
repeats:YES];
} - (void)animateWithTimer
{
if (_step == 0) {
[_timer invalidate];
[_imageView removeFromSuperview];
} _imageView.transform = CGAffineTransformRotate(CGAffineTransformScale(_imageView.transform, 0.98, 0.98), ((10 * M_PI) / 180.0));
_imageView.alpha *= 0.98;
_step--;
}

虽然没有使用UIView封装的方法,但是也简单的实现了一个动画效果。




以上就是本篇博客全部内容,欢迎指正和交流。转载注明出处~