UIView基础动画

设置 UIView 形变动画有两种经常用到的属性,.frame,.transform,所以有的人也可以分别称之为:

  1. frame 动画
  2. transform 动画

这两种动画只需要在动画语法中适当的位置,基于 UIView 和 CALayer 的属性设置变化值即可。这种动画,不需要调用核心动画 CAAnimation 里面的专用类和 API。

其中,frame 动画设置方式有限,必须确切地制定形变前后的 frame,平移还好,特别是旋转的时候,只能通过数学知识计算出新的 frame。这就得不偿失了。所以,更多的时候,当涉及一些 frame,bounds,center 的改变或是形变的时候可以用 transform 来取代 frame。

1.设置 UIView 动画的两种语法形式

  • begin --- commit
//偏移动画
[UIView beginAnimations:@"move" context:nil];  
[UIView setAnimationDuration:2];  
[UIView setAnimationDelegate:self];  
imageContainView.frame = CGRectMake(80, 80, 200, 200);  
[label1 setBackgroundColor:[UIColor yellowColor]];  
[label1 setTextColor:[UIColor redColor]];  
[UIView commitAnimations]; 
  • animations block
//缩放动画
view.transform = CGAffineTransformIdentity;
[UIView animateWithDuration:1.0f animations:^{
   view.transform = CGAffineTransformMakeScale(2.0f, 2.0f);
}];

2.设置属性形变动画的两种类型

  • UIView 的 CGAffineTransform 类型属性: animatedView.transform
    一般是 View 的旋转,拉伸移动等属性,是二维的,通常使用都是前缀 CGAffineTransform 的类。
CGAffineTransform transform = CGAffineTransformScale(imageContainView.transform, 1.2, 1.2); 
[UIView beginAnimations: @"scale"context: nil]; 
[UIView setAnimationDuration: 2];
[UIView setAnimationDelegate: self];
[imageView setTransform: transform]; 
[UIView commitAnimations];
  • CALayer 的 CATransform3D 类型属性:animaView.layer.transform 通过 .layer.transform 可以在 3D 模式下面的变化,通常使用的都是前缀为 CATransform3D 的类。
imageView.layer.transform =  CATransform3DIdentity;
[UIView animateWithDuration:1.0f animations:^{
      imageView.layer.transform = CATransform3DMakeScale(2.0, 2.0, 1.0);
}];

3.与动画相关的属性

3.1 下面是 begin-commit类型动画的一些属性介绍

UIView.beginAnimations("move", context: nil)
UIView.setAnimationDuration(5)                                  //  动画的持续时间,秒为单位
UIView.setAnimationDelegate(self)                               //  设置动画的代理对象
UIView.setAnimationDelay(1)                                     //  动画延迟delay秒后再开始
UIView.setAnimationWillStart(#selector(willBeginAction))        //  设置动画代理对象,当动画开始时会发消息给代理对象
UIView.setAnimationDidStop(#selector(didStopAction))            //  设置动画代理对象,当动画结束时会发消息给代理对象
UIView.setAnimationCurve(UIViewAnimationCurve.easeOut)          //  动画的节奏控制 (淡入淡出等)
UIView.setAnimationRepeatCount(2)                               //  动画的重复次数
UIView.setAnimationBeginsFromCurrentState(false)                //  设置动画的开始是从现在的状态开始, 默认是 false
UIView.setAnimationRepeatAutoreverses(true)                     //  如果设置为YES,代表动画每次重复执行的效果会跟上一次相反
UIView.setAnimationsEnabled(true)                               //  用来开启或禁止动画显示
UIView.commitAnimations()

3.2 下面是 block类型动画的一些属性介绍

// 最基本的用法
UIView.animate(withDuration: TimeInterval,
                 animations: ()->Void)
                 
//  多了个动画完成时的回调
UIView.animate(withDuration: TimeInterval,
                 animations: ()->Void,
                 completion: ()->Void)

//  带动画曲线的动画
UIView.animate(withDuration: TimeInterval,
                      delay: TimeInterval,
                    options: UIViewAnimationOptions,
                 animations: ()->Void,
                 completion: (()->Void)?)

3.3 上面的几种block都是比较基础的,接下来还有三个是动画效果更好点的

3.3.1 弹性动画
UIView.animate(withDuration: TimeInterval,
                      delay: TimeInterval,
     usingSpringWithDamping: 0,
      initialSpringVelocity: 0,
                    options: UIViewAnimationOptions,
                 animations: ()->Void,
                 completion: (()->Void)?)

这个动画真的是推荐,简单效果还好用。很多地方稍微加上点弹性动画,感觉效果会好很多。其中主要有2个参数:

//  usingSpringWithDamping 的范围为0.0f到1.0f,数值越小「弹簧」的振动效果越明显
//  initialSpringVelocity 表示初始的速度,数值越大一开始移动越快
3.3.2 关键帧动画
UIView.animateKeyframes(withDuration: TimeInterval,
                               delay: TimeInterval,
                             options: UIViewKeyframeAnimationOptions,
                          animations: ()->Void,
                          completion: (()->Void)?)
                          
// 添加帧
UIView.addKeyframe(withRelativeStartTime: Double,
                        relativeDuration: Double,
                              animations: ()->Void)

可以使用这个动画来实现一些分时段的动画。其中关键的是下面两个参数:

//withRelativeStartTime:开始时间
//relativeDuration:持续时间

注意这里的开始时间和持续时间的范围是0.0f到1.0f,对应的是设置的总的动画时间的百分比时间。比如总的动画时间是5s,设置的开始时间是0.5,持续时间是0.25,那么实际的开始时间就是2.5s的时候,持续时间是1.25s。

UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.25, animations: {
    self.loginView.backgroundColor = UIColor.blue
})
UIView.addKeyframe(withRelativeStartTime: 0.25, relativeDuration: 0.25, animations: {
    self.loginView.backgroundColor = UIColor.brown
})
UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.25, animations: {
    self.loginView.backgroundColor = UIColor.red
})
UIView.addKeyframe(withRelativeStartTime: 0.75, relativeDuration: 0.25, animations: {
    self.loginView.backgroundColor = UIColor.yellow
})

3.3.3 转场动画
UIView.transition(with: UIView,
              duration: TimeInterval,
               options: UIViewAnimationOptions,
            animations: ()->Void,
            completion: (()->Void)?)

当做一些页面上的翻页,翻转时可以用到。UIViewAnimationOptions是一个枚举值,可通过数组结合起来使用

UIViewAnimationOptionLayoutSubviews            //提交动画的时候布局子控件,表示子控件将和父控件一同动画。
UIViewAnimationOptionAllowUserInteraction      //动画时允许用户交流,比如触摸
UIViewAnimationOptionBeginFromCurrentState     //从当前状态开始动画
UIViewAnimationOptionRepeat                    //动画无限重复
UIViewAnimationOptionAutoreverse               //执行动画回路,前提是设置动画无限重复
UIViewAnimationOptionOverrideInheritedDuration //忽略外层动画嵌套的执行时间
UIViewAnimationOptionOverrideInheritedCurve    //忽略外层动画嵌套的时间变化曲线
UIViewAnimationOptionAllowAnimatedContent      //通过改变属性和重绘实现动画效果,如果key没有提交动画将使用快照
UIViewAnimationOptionShowHideTransitionViews   //用显隐的方式替代添加移除图层的动画效果
UIViewAnimationOptionOverrideInheritedOptions  //忽略嵌套继承的选项

//时间函数曲线相关
UIViewAnimationOptionCurveEaseInOut            //时间曲线函数,缓入缓出,中间快
UIViewAnimationOptionCurveEaseIn               //时间曲线函数,由慢到特别快(缓入快出)
UIViewAnimationOptionCurveEaseOut              //时间曲线函数,由快到慢(快入缓出)
UIViewAnimationOptionCurveLinear               //时间曲线函数,匀速

//转场动画相关的
UIViewAnimationOptionTransitionNone            //无转场动画
UIViewAnimationOptionTransitionFlipFromLeft    //转场从左翻转
 UIViewAnimationOptionTransitionFlipFromRight   //转场从右翻转
UIViewAnimationOptionTransitionCurlUp          //上卷转场
UIViewAnimationOptionTransitionCurlDown        //下卷转场
UIViewAnimationOptionTransitionCrossDissolve   //转场交叉消失
UIViewAnimationOptionTransitionFlipFromTop     //转场从上翻转
UIViewAnimationOptionTransitionFlipFromBottom  //转场从下翻转

还有一个转场动画也是用在这个方法里的

[UIView transitionFromView: toView: duration: options: completion:^(BOOL finished) {}];

这个方法的效果是插入一面视图,移除旧的视图,期间可以使用一些转场动画效果。

3.4 CGAffineTransform相关属性

3.4.1 CGAffineTransform的改变主要包括以下三种
self.loginBtn.transform = CGAffineTransform(translationX: 200, y: 200)          // 平移
self.loginBtn.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 4)      // 旋转
self.loginBtn.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)                // 缩放

但是上面的方法只能支持单次形变,如果想要持续的,在之前形变的基础上继续变化的话,需要调用下面的方法。

//  通过关联我们上次变换后的CGAffineTransform实例, 就可以实现每次都在上次变换的基础上再进行变换
self.loginBtn.transform = CGAffineTransform(scaleX: 1.2, y: 1.2).concatenating(self.loginBtn.transform)
self.loginBtn.transform = CGAffineTransform(translationX: 0, y: -50).concatenating(self.loginBtn.transform)
self.loginBtn.transform = CGAffineTransform(rotationAngle: CGFloat.pi).concatenating(self.loginBtn.transform)

当想要反向变化时,可以用下面的属性

//   对 调用该方法的 CGAffineTransform实例 进行取反 并返回
self.loginBtn.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2).inverted()

最后,如果想要还原,可以使用下面的属性

self.loginBtn.transform = CGAffineTransform.identity

3.5 CATransform3D相关属性

同样的,和CGAffineTransform差不多,CATransform3D也支持平移,缩放和旋转。同样有支持一次形变和持续形变的属性,如下:

//  值范围-1 — 1之间
//  左手定则。以绕y轴旋转为例,当参数y为正时,左手大拇指指向y轴正向(向下),手掌弯曲方向即为旋转方向,此时从上往下看是逆时针方向。若y参数为负,将大拇指指向y轴负向(向上),此时从上往下看是顺时针方向。 绕x轴z轴旋转判断方法相同。
self.loginBtn.layer.transform = CATransform3DRotate(self.loginBtn.layer.transform, CGFloat.pi / 2, 0, 0, -1)    // 可持续形变
self.loginBtn.layer.transform = CATransform3DMakeRotation(CGFloat.pi / 2, 0, 0, -1)                             // 单次形变
                
//  sx、sy、sz参数对应x、y、z轴的比例缩放,>0为正向比例缩放,<0为反向比例缩放。
self.loginBtn.layer.transform = CATransform3DScale(self.loginBtn.layer.transform, 1.2, 0.8, 2)                  // 可持续形变
self.loginBtn.layer.transform = CATransform3DMakeScale(1.2, 0.8, 1)                                             // 单次形变
                
//  对应CATransform3D的公式,tx、ty、tz参数分别用于x平移、y平移、z平移。x、y的平移比较好理解,对于tz来说,值越大,那么图层就越往外(接近屏幕),值越小,图层越往里(屏幕里)。
self.loginBtn.layer.transform = CATransform3DTranslate(self.loginBtn.layer.transform, 5, -20, 100)              // 可持续形变
self.loginBtn.layer.transform = CATransform3DMakeTranslation(5, -20, 100)                                       // 单次形变

想要效果叠加的话,也可以使用如下属性

let scaleTransform = CATransform3DMakeTranslation(1.2, 0.8, 10)
self.loginBtn.layer.transform = CATransform3DConcat(self.loginBtn.layer.transform, scaleTransform)

let translateTransform = CATransform3DMakeTranslation(10, -20, 50)
self.loginBtn.layer.transform = CATransform3DConcat(self.loginBtn.layer.transform, translateTransform)


let rotateTransform = CATransform3DMakeRotation(CGFloat.pi / 2, 1, 0, 0)
self.loginBtn.layer.transform = CATransform3DConcat(self.loginBtn.layer.transform, rotateTransform)

想要3D仿射效果反转(反效果,比如原来向左移动的,变成向右),可以使用以下属性

self.loginBtn.layer.transform = CATransform3DInvert(self.loginBtn.layer.transform)

最后,想要还原的话,可以使用以下属性

self.loginBtn.layer.transform = CATransform3DIdentity

4.注意点

在实际操作的时候,发现一个问题就是,用xib拖的控件,在做改变其frame的时候,并没有动画效果。后来查资料发现,需要把控件的宽高或者距离的约束拖到类文件中成为属性,然后再对约束进行操作,最后还要记得对控件的父view执行layoutIfNeeded。代码如下

UIView.animate(withDuration: 3, animations: {
    //  进行控件的约束属性操作
    self.viewLeftLeading.constant = 100
                    
    self.view.layoutIfNeeded() // 在控件的父view上执行layoutIfNeeded
})
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,519评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,842评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,544评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,742评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,646评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,027评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,169评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,324评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,268评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,299评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,996评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,591评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,911评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,288评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,871评论 2 341

推荐阅读更多精彩内容