当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS核心动画高级技巧-5

iOS核心动画高级技巧-5

2019年11月28日  | 移动技术网IT编程  | 我要评论

9. 图层时间

图层时间

时间和空间最大的区别在于,时间不能被复用 -- 弗斯特梅里克

在上面两章中,我们探讨了可以用caanimation和它的子类实现的多种图层动画。动画的发生是需要持续一段时间的,所以计时对整个概念来说至关重要。在这一章中,我们来看看camediatiming,看看core animation是如何跟踪时间的。

9.1 camediatiming协议

camediatiming`协议

camediatiming协议定义了在一段动画内用来控制逝去时间的属性的集合,calayercaanimation都实现了这个协议,所以时间可以被任意基于一个图层或者一段动画的类控制。

持续和重复

我们在第八章“显式动画”中简单提到过duration(camediatiming的属性之一),duration是一个cftimeinterval的类型(类似于nstimeinterval的一种双精度浮点类型),对将要进行的动画的一次迭代指定了时间。

这里的一次迭代是什么意思呢?camediatiming另外还有一个属性叫做repeatcount,代表动画重复的迭代次数。如果duration是2,repeatcount设为3.5(三个半迭代),那么完整的动画时长将是7秒。

一个开发者,有一个学习的氛围跟一个交流圈子特别重要,这是一个我的ios交流群:1012951431, 分享bat,阿里面试题、面试经验,讨论技术, 大家一起交流学习成长!希望帮助开发者少走弯路。

durationrepeatcount默认都是0。但这不意味着动画时长为0秒,或者0次,这里的0仅仅代表了“默认”,也就是0.25秒和1次,你可以用一个简单的测试来尝试为这两个属性赋多个值,如清单9.1,图9.1展示了程序的结果。

清单9.1 测试durationrepeatcount

@interface viewcontroller ()

@property (nonatomic, weak) iboutlet uiview *containerview;
@property (nonatomic, weak) iboutlet uitextfield *durationfield;
@property (nonatomic, weak) iboutlet uitextfield *repeatfield;
@property (nonatomic, weak) iboutlet uibutton *startbutton;
@property (nonatomic, strong) calayer *shiplayer;

@end

@implementation viewcontroller

- (void)viewdidload
{
    [super viewdidload];
    //add the ship
    self.shiplayer = [calayer layer];
    self.shiplayer.frame = cgrectmake(0, 0, 128, 128);
    self.shiplayer.position = cgpointmake(150, 150);
    self.shiplayer.contents = (__bridge id)[uiimage imagenamed: @"ship.png"].cgimage;
    [self.containerview.layer addsublayer:self.shiplayer];
}

- (void)setcontrolsenabled:(bool)enabled
{
    for (uicontrol *control in @[self.durationfield, self.repeatfield, self.startbutton]) {
        control.enabled = enabled;
        control.alpha = enabled? 1.0f: 0.25f;
    }
}

- (ibaction)hidekeyboard
{
    [self.durationfield resignfirstresponder];
    [self.repeatfield resignfirstresponder];
}

- (ibaction)start
{
    cftimeinterval duration = [self.durationfield.text doublevalue];
    float repeatcount = [self.repeatfield.text floatvalue];
    //animate the ship rotation
    cabasicanimation *animation = [cabasicanimation animation];
    animation.keypath = @"transform.rotation";
    animation.duration = duration;
    animation.repeatcount = repeatcount;
    animation.byvalue = @(m_pi * 2);
    animation.delegate = self;
    [self.shiplayer addanimation:animation forkey:@"rotateanimation"];
    //disable controls
    [self setcontrolsenabled:no];
}

- (void)animationdidstop:(caanimation *)anim finished:(bool)flag
{
    //reenable controls
    [self setcontrolsenabled:yes];
}

@end

 

图9.2 摆动门的动画

对门进行摆动的代码见清单9.2。我们用了autoreverses来使门在打开后自动关闭,在这里我们把repeatduration设置为infinity,于是动画无限循环播放,设置repeatcountinfinity也有同样的效果。注意repeatcount和repeatduration可能会相互冲突,所以你只要对其中一个指定非零值。对两个属性都设置非0值的行为没有被定义。

清单9.2 使用autoreverses属性实现门的摇摆

@interface viewcontroller ()

@property (nonatomic, weak) uiview *containerview;

@end

@implementation viewcontroller

- (void)viewdidload
{
    [super viewdidload];
    //add the door
    calayer *doorlayer = [calayer layer];
    doorlayer.frame = cgrectmake(0, 0, 128, 256);
    doorlayer.position = cgpointmake(150 - 64, 150);
    doorlayer.anchorpoint = cgpointmake(0, 0.5);
    doorlayer.contents = (__bridge id)[uiimage imagenamed: @"door.png"].cgimage;
    [self.containerview.layer addsublayer:doorlayer];
    //apply perspective transform
    catransform3d perspective = catransform3didentity;
    perspective.m34 = -1.0 / 500.0;
    self.containerview.layer.sublayertransform = perspective;
    //apply swinging animation
    cabasicanimation *animation = [cabasicanimation animation];
    animation.keypath = @"transform.rotation.y";
    animation.tovalue = @(-m_pi_2);
    animation.duration = 2.0;
    animation.repeatduration = infinity;
    animation.autoreverses = yes;
    [doorlayer addanimation:animation forkey:nil];
}

@end

 

相对时间

每次讨论到core animation,时间都是相对的,每个动画都有它自己描述的时间,可以独立地加速,延时或者偏移。

begintime指定了动画开始之前的的延迟时间。这里的延迟从动画添加到可见图层的那一刻开始测量,默认是0(就是说动画会立刻执行)。

speed是一个时间的倍数,默认1.0,减少它会减慢图层/动画的时间,增加它会加快速度。如果2.0的速度,那么对于一个duration为1的动画,实际上在0.5秒的时候就已经完成了。

timeoffsetbegintime类似,但是和增加begintime导致的延迟动画不同,增加timeoffset只是让动画快进到某一点,例如,对于一个持续1秒的动画来说,设置timeoffset为0.5意味着动画将从一半的地方开始。

begintime不同的是,timeoffset并不受speed的影响。所以如果你把speed设为2.0,把timeoffset设置为0.5,那么你的动画将从动画最后结束的地方开始,因为1秒的动画实际上被缩短到了0.5秒。然而即使使用了timeoffset让动画从结束的地方开始,它仍然播放了一个完整的时长,这个动画仅仅是循环了一圈,然后从头开始播放。

可以用清单9.3的测试程序验证一下,设置speedtimeoffset滑块到随意的值,然后点击播放来观察效果(见图9.3)

清单9.3 测试timeoffsetspeed属性

@interface viewcontroller ()

@property (nonatomic, weak) iboutlet uiview *containerview;
@property (nonatomic, weak) iboutlet uilabel *speedlabel;
@property (nonatomic, weak) iboutlet uilabel *timeoffsetlabel;
@property (nonatomic, weak) iboutlet uislider *speedslider;
@property (nonatomic, weak) iboutlet uislider *timeoffsetslider;
@property (nonatomic, strong) uibezierpath *bezierpath;
@property (nonatomic, strong) calayer *shiplayer;

@end

@implementation viewcontroller

- (void)viewdidload
{
    [super viewdidload];
    //create a path
    self.bezierpath = [[uibezierpath alloc] init];
    [self.bezierpath movetopoint:cgpointmake(0, 150)];
    [self.bezierpath addcurvetopoint:cgpointmake(300, 150) controlpoint1:cgpointmake(75, 0) controlpoint2:cgpointmake(225, 300)];
    //draw the path using a cashapelayer
    cashapelayer *pathlayer = [cashapelayer layer];
    pathlayer.path = self.bezierpath.cgpath;
    pathlayer.fillcolor = [uicolor clearcolor].cgcolor;
    pathlayer.strokecolor = [uicolor redcolor].cgcolor;
    pathlayer.linewidth = 3.0f;
    [self.containerview.layer addsublayer:pathlayer];
    //add the ship
    self.shiplayer = [calayer layer];
    self.shiplayer.frame = cgrectmake(0, 0, 64, 64);
    self.shiplayer.position = cgpointmake(0, 150);
    self.shiplayer.contents = (__bridge id)[uiimage imagenamed: @"ship.png"].cgimage;
    [self.containerview.layer addsublayer:self.shiplayer];
    //set initial values
    [self updatesliders];
}

- (ibaction)updatesliders
{
    cftimeinterval timeoffset = self.timeoffsetslider.value;
    self.timeoffsetlabel.text = [nsstring stringwithformat:@"%0.2f", timeoffset];
    float speed = self.speedslider.value;
    self.speedlabel.text = [nsstring stringwithformat:@"%0.2f", speed];
}

- (ibaction)play
{
    //create the keyframe animation
    cakeyframeanimation *animation = [cakeyframeanimation animation];
    animation.keypath = @"position";
    animation.timeoffset = self.timeoffsetslider.value;
    animation.speed = self.speedslider.value;
    animation.duration = 1.0;
    animation.path = self.bezierpath.cgpath;
    animation.rotationmode = kcaanimationrotateauto;
    animation.removedoncompletion = no;
    [self.shiplayer addanimation:animation forkey:@"slide"];
}

@end

 

9.2 层级关系时间

层级关系时间

9.3 手动动画

手动动画

timeoffset一个很有用的功能在于你可以它可以让你手动控制动画进程,通过设置speed为0,可以禁用动画的自动播放,然后来使用timeoffset来来回显示动画序列。这可以使得运用手势来手动控制动画变得很简单。

举个简单的例子:还是之前关门的动画,修改代码来用手势控制动画。我们给视图添加一个uipangesturerecognizer,然后用timeoffset左右摇晃。

因为在动画添加到图层之后不能再做修改了,我们来通过调整layertimeoffset达到同样的效果(清单9.4)。

清单9.4 通过触摸手势手动控制动画

@interface viewcontroller ()

@property (nonatomic, weak) uiview *containerview;
@property (nonatomic, strong) calayer *doorlayer;

@end

@implementation viewcontroller

- (void)viewdidload
{
    [super viewdidload];
    //add the door
    self.doorlayer = [calayer layer];
    self.doorlayer.frame = cgrectmake(0, 0, 128, 256);
    self.doorlayer.position = cgpointmake(150 - 64, 150);
    self.doorlayer.anchorpoint = cgpointmake(0, 0.5);
    self.doorlayer.contents = (__bridge id)[uiimage imagenamed:@"door.png"].cgimage;
    [self.containerview.layer addsublayer:self.doorlayer];
    //apply perspective transform
    catransform3d perspective = catransform3didentity;
    perspective.m34 = -1.0 / 500.0;
    self.containerview.layer.sublayertransform = perspective;
    //add pan gesture recognizer to handle swipes
    uipangesturerecognizer *pan = [[uipangesturerecognizer alloc] init];
    [pan addtarget:self action:@selector(pan:)];
    [self.view addgesturerecognizer:pan];
    //pause all layer animations
    self.doorlayer.speed = 0.0;
    //apply swinging animation (which won't play because layer is paused)
    cabasicanimation *animation = [cabasicanimation animation];
    animation.keypath = @"transform.rotation.y";
    animation.tovalue = @(-m_pi_2);
    animation.duration = 1.0;
    [self.doorlayer addanimation:animation forkey:nil];
}

- (void)pan:(uipangesturerecognizer *)pan
{
    //get horizontal component of pan gesture
    cgfloat x = [pan translationinview:self.view].x;
    //convert from points to animation duration //using a reasonable scale factor
    x /= 200.0f;
    //update timeoffset and clamp result
    cftimeinterval timeoffset = self.doorlayer.timeoffset;
    timeoffset = min(0.999, max(0.0, timeoffset - x));
    self.doorlayer.timeoffset = timeoffset;
    //reset pan gesture
    [pan settranslation:cgpointzero inview:self.view];
}

@end

 

这其实是个小诡计,也许相对于设置个动画然后每次显示一帧而言,用移动手势来直接设置门的transform会更简单。

在这个例子中的确是这样,但是对于比如说关键这这样更加复杂的情况,或者有多个图层的动画组,相对于实时计算每个图层的属性而言,这就显得方便的多了。

9.4 总结

总结

在这一章,我们了解了camediatiming协议,以及core animation用来操作时间控制动画的机制。在下一章,我们将要接触缓冲,另一个用来使动画更加真实的操作时间的技术。

10. 缓冲

缓冲

生活和艺术一样,最美的永远是曲线。 -- 爱德华布尔沃 - 利顿

在第九章“图层时间”中,我们讨论了动画时间和camediatiming协议。现在我们来看一下另一个和时间相关的机制--所谓的缓冲。core animation使用缓冲来使动画移动更平滑更自然,而不是看起来的那种机械和人工,在这一章我们将要研究如何对你的动画控制和自定义缓冲曲线。

10.1 动画速度

动画速度

动画实际上就是一段时间内的变化,这就暗示了变化一定是随着某个特定的速率进行。速率由以下公式计算而来:

velocity = change / time

 

这里的变化可以指的是一个物体移动的距离,时间指动画持续的时长,用这样的一个移动可以更加形象的描述(比如positionbounds属性的动画),但实际上它应用于任意可以做动画的属性(比如coloropacity)。

上面的等式假设了速度在整个动画过程中都是恒定不变的(就如同第八章“显式动画”的情况),对于这种恒定速度的动画我们称之为“线性步调”,而且从技术的角度而言这也是实现动画最简单的方式,但也是完全不真实的一种效果。

考虑一个场景,一辆车行驶在一定距离内,它并不会一开始就以60mph的速度行驶,然后到达终点后突然变成0mph。一是因为需要无限大的加速度(即使是最好的车也不会在0秒内从0跑到60),另外不然的话会干死所有乘客。在现实中,它会慢慢地加速到全速,然后当它接近终点的时候,它会慢慢地减速,直到最后停下来。

那么对于一个掉落到地上的物体又会怎样呢?它会首先停在空中,然后一直加速到落到地面,然后突然停止(然后由于积累的动能转换伴随着一声巨响,砰!)。

现实生活中的任何一个物体都会在运动中加速或者减速。那么我们如何在动画中实现这种加速度呢?一种方法是使用物理引擎来对运动物体的摩擦和动量来建模,然而这会使得计算过于复杂。我们称这种类型的方程为缓冲函数,幸运的是,core animation内嵌了一系列标准函数提供给我们使用。

camediatimingfunction

那么该如何使用缓冲方程式呢?首先需要设置caanimation的timingfunction属性,是camediatimingfunction类的一个对象。如果想改变隐式动画的计时函数,同样也可以使用catransaction+setanimationtimingfunction:方法。

这里有一些方式来创建camediatimingfunction,最简单的方式是调用+timingfunctionwithname:的构造方法。这里传入如下几个常量之一:

kcamediatimingfunctionlinear 
kcamediatimingfunctioneasein 
kcamediatimingfunctioneaseout 
kcamediatimingfunctioneaseineaseout
kcamediatimingfunctiondefault

 

kcamediatimingfunctionlinear选项创建了一个线性的计时函数,同样也是caanimation的timingfunction属性为空时候的默认函数。线性步调对于那些立即加速并且保持匀速到达终点的场景会有意义(例如射出枪膛的子弹),但是默认来说它看起来很奇怪,因为对大多数的动画来说确实很少用到。

kcamediatimingfunctioneasein常量创建了一个慢慢加速然后突然停止的方法。对于之前提到的自由落体的例子来说很适合,或者比如对准一个目标的导弹的发射。

kcamediatimingfunctioneaseout则恰恰相反,它以一个全速开始,然后慢慢减速停止。它有一个削弱的效果,应用的场景比如一扇门慢慢地关上,而不是砰地一声。

kcamediatimingfunctioneaseineaseout创建了一个慢慢加速然后再慢慢减速的过程。这是现实世界大多数物体移动的方式,也是大多数动画来说最好的选择。如果只可以用一种缓冲函数的话,那就必须是它了。那么你会疑惑为什么这不是默认的选择,实际上当使用uiview的动画方法时,他的确是默认的,但当创建caanimation的时候,就需要手动设置它了。

最后还有一个kcamediatimingfunctiondefault,它和kcamediatimingfunctioneaseineaseout很类似,但是加速和减速的过程都稍微有些慢。它和kcamediatimingfunctioneaseineaseout的区别很难察觉,可能是苹果觉得它对于隐式动画来说更适合(然后对uikit就改变了想法,而是使用kcamediatimingfunctioneaseineaseout作为默认效果),虽然它的名字说是默认的,但还是要记住当创建显式的caanimation它并不是默认选项(换句话说,默认的图层行为动画用kcamediatimingfunctiondefault作为它们的计时方法)。

你可以使用一个简单的测试工程来实验一下(清单10.1),在运行之前改变缓冲函数的代码,然后点击任何地方来观察图层是如何通过指定的缓冲移动的。

清单10.1 缓冲函数的简单测试

@interface viewcontroller ()

@property (nonatomic, strong) calayer *colorlayer;

@end

@implementation viewcontroller

- (void)viewdidload
{
    [super viewdidload];
    //create a red layer
    self.colorlayer = [calayer layer];
    self.colorlayer.frame = cgrectmake(0, 0, 100, 100);
    self.colorlayer.position = cgpointmake(self.view.bounds.size.width/2.0, self.view.bounds.size.height/2.0);
    self.colorlayer.backgroundcolor = [uicolor redcolor].cgcolor;
    [self.view.layer addsublayer:self.colorlayer];
}

- (void)touchesbegan:(nsset *)touches withevent:(uievent *)event
{
    //configure the transaction
    [catransaction begin];
    [catransaction setanimationduration:1.0];
    [catransaction setanimationtimingfunction:[camediatimingfunction functionwithname:kcamediatimingfunctioneaseout]];
    //set the position
    self.colorlayer.position = [[touches anyobject] locationinview:self.view];
    //commit transaction
    [catransaction commit];
}

@end

 

uiview的动画缓冲

uikit的动画也同样支持这些缓冲方法的使用,尽管语法和常量有些不同,为了改变uiview动画的缓冲选项,给options参数添加如下常量之一:

uiviewanimationoptioncurveeaseinout 
uiviewanimationoptioncurveeasein 
uiviewanimationoptioncurveeaseout 
uiviewanimationoptioncurvelinear

 

它们和camediatimingfunction紧密关联,uiviewanimationoptioncurveeaseinout是默认值(这里没有kcamediatimingfunctiondefault相对应的值了)。

具体使用方法见清单10.2(注意到这里不再使用uiview额外添加的图层,因为uikit的动画并不支持这类图层)。

清单10.2 使用uikit动画的缓冲测试工程

@interface viewcontroller ()

@property (nonatomic, strong) uiview *colorview;

@end

@implementation viewcontroller

- (void)viewdidload
{
    [super viewdidload];
    //create a red layer
    self.colorview = [[uiview alloc] init];
    self.colorview.bounds = cgrectmake(0, 0, 100, 100);
    self.colorview.center = cgpointmake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
    self.colorview.backgroundcolor = [uicolor redcolor];
    [self.view addsubview:self.colorview];
}

- (void)touchesbegan:(nsset *)touches withevent:(uievent *)event
{
    //perform the animation
    [uiview animatewithduration:1.0 delay:0.0
                        options:uiviewanimationoptioncurveeaseout
                     animations:^{
                            //set the position
                            self.colorview.center = [[touches anyobject] locationinview:self.view];
                        }
                     completion:null];

}

@end

 

缓冲和关键帧动画

或许你会回想起第八章里面颜色切换的关键帧动画由于线性变换的原因(见清单8.5)看起来有些奇怪,使得颜色变换非常不自然。为了纠正这点,我们来用更加合适的缓冲方法,例如kcamediatimingfunctioneasein,给图层的颜色变化添加一点脉冲效果,让它更像现实中的一个彩色灯泡。

我们不想给整个动画过程应用这个效果,我们希望对每个动画的过程重复这样的缓冲,于是每次颜色的变换都会有脉冲效果。

cakeyframeanimation有一个nsarray类型的timingfunctions属性,我们可以用它来对每次动画的步骤指定不同的计时函数。但是指定函数的个数一定要等于keyframes数组的元素个数减一,因为它是描述每一帧之间动画速度的函数。

在这个例子中,我们自始至终想使用同一个缓冲函数,但我们同样需要一个函数的数组来告诉动画不停地重复每个步骤,而不是在整个动画序列只做一次缓冲,我们简单地使用包含多个相同函数拷贝的数组就可以了(见清单10.3)。

运行更新后的代码,你会发现动画看起来更加自然了。

清单10.3 对cakeyframeanimation使用camediatimingfunction

@interface viewcontroller ()

@property (nonatomic, weak) iboutlet uiview *layerview;
@property (nonatomic, weak) iboutlet calayer *colorlayer;

@end

@implementation viewcontroller

- (void)viewdidload
{
    [super viewdidload];
    //create sublayer
    self.colorlayer = [calayer layer];
    self.colorlayer.frame = cgrectmake(50.0f, 50.0f, 100.0f, 100.0f);
    self.colorlayer.backgroundcolor = [uicolor bluecolor].cgcolor;
    //add it to our view
    [self.layerview.layer addsublayer:self.colorlayer];
}

- (ibaction)changecolor
{
    //create a keyframe animation
    cakeyframeanimation *animation = [cakeyframeanimation animation];
    animation.keypath = @"backgroundcolor";
    animation.duration = 2.0;
    animation.values = @[
                         (__bridge id)[uicolor bluecolor].cgcolor,
                         (__bridge id)[uicolor redcolor].cgcolor,
                         (__bridge id)[uicolor greencolor].cgcolor,
                         (__bridge id)[uicolor bluecolor].cgcolor ];
    //add timing function
    camediatimingfunction *fn = [camediatimingfunction functionwithname: kcamediatimingfunctioneasein];
    animation.timingfunctions = @[fn, fn, fn];
    //apply animation to layer
    [self.colorlayer addanimation:animation forkey:nil];
}

@end

 

10.2 自定义缓冲函数

自定义缓冲函数

在第八章中,我们给时钟项目添加了动画。看起来很赞,但是如果有合适的缓冲函数就更好了。在显示世界中,钟表指针转动的时候,通常起步很慢,然后迅速啪地一声,最后缓冲到终点。但是标准的缓冲函数在这里每一个适合它,那该如何创建一个新的呢?

除了+functionwithname:之外,camediatimingfunction同样有另一个构造函数,一个有四个浮点参数的+functionwithcontrolpoints::::(注意这里奇怪的语法,并没有包含具体每个参数的名称,这在objective-c中是合法的,但是却违反了苹果对方法命名的指导方针,而且看起来是一个奇怪的设计)。

使用这个方法,我们可以创建一个自定义的缓冲函数,来匹配我们的时钟动画,为了理解如何使用这个方法,我们要了解一些camediatimingfunction是如何工作的。

三次贝塞尔曲线

camediatimingfunction函数的主要原则在于它把输入的时间转换成起点和终点之间成比例的改变。我们可以用一个简单的图标来解释,横轴代表时间,纵轴代表改变的量,于是线性的缓冲就是一条从起点开始的简单的斜线(图10.1)。

图10.2 三次贝塞尔缓冲函数

实际上它是一个很奇怪的函数,先加速,然后减速,最后快到达终点的时候又加速,那么标准的缓冲函数又该如何用图像来表示呢?

camediatimingfunction有一个叫做-getcontrolpointatindex:values:的方法,可以用来检索曲线的点,这个方法的设计的确有点奇怪(或许也就只有苹果能回答为什么不简单返回一个cgpoint),但是使用它我们可以找到标准缓冲函数的点,然后用uibezierpathcashapelayer来把它画出来。

曲线的起始和终点始终是{0, 0}和{1, 1},于是我们只需要检索曲线的第二个和第三个点(控制点)。具体代码见清单10.4。所有的标准缓冲函数的图像见图10.3。

清单10.4 使用uibezierpath绘制camediatimingfunction

@interface viewcontroller ()

@property (nonatomic, weak) iboutlet uiview *layerview;

@end

@implementation viewcontroller

- (void)viewdidload
{
    [super viewdidload];
    //create timing function
    camediatimingfunction *function = [camediatimingfunction functionwithname: kcamediatimingfunctioneaseout];
    //get control points
    cgpoint controlpoint1, controlpoint2;
    [function getcontrolpointatindex:1 values:(float *)&controlpoint1];
    [function getcontrolpointatindex:2 values:(float *)&controlpoint2];
    //create curve
    uibezierpath *path = [[uibezierpath alloc] init];
    [path movetopoint:cgpointzero];
    [path addcurvetopoint:cgpointmake(1, 1)
            controlpoint1:controlpoint1 controlpoint2:controlpoint2];
    //scale the path up to a reasonable size for display
    [path applytransform:cgaffinetransformmakescale(200, 200)];
    //create shape layer
    cashapelayer *shapelayer = [cashapelayer layer];
    shapelayer.strokecolor = [uicolor redcolor].cgcolor;
    shapelayer.fillcolor = [uicolor clearcolor].cgcolor;
    shapelayer.linewidth = 4.0f;
    shapelayer.path = path.cgpath;
    [self.layerview.layer addsublayer:shapelayer];
    //flip geometry so that 0,0 is in the bottom-left
    self.layerview.layer.geometryflipped = yes;
}

@end

 

图10.4 自定义适合时钟的缓冲函数

清单10.5 添加了自定义缓冲函数的时钟程序

- (void)setangle:(cgfloat)angle forhand:(uiview *)handview animated:(bool)animated
{
    //generate transform
    catransform3d transform = catransform3dmakerotation(angle, 0, 0, 1);
    if (animated) {
        //create transform animation
        cabasicanimation *animation = [cabasicanimation animation];
        animation.keypath = @"transform";
        animation.fromvalue = [handview.layer.presentationlayer valueforkey:@"transform"];
        animation.tovalue = [nsvalue valuewithcatransform3d:transform];
        animation.duration = 0.5;
        animation.delegate = self;
        animation.timingfunction = [camediatimingfunction functionwithcontrolpoints:1 :0 :0.75 :1];
        //apply animation
        handview.layer.transform = transform;
        [handview.layer addanimation:animation forkey:nil];
    } else {
        //set transform directly
        handview.layer.transform = transform;
    }
}

 

更加复杂的动画曲线

考虑一个橡胶球掉落到坚硬的地面的场景,当开始下落的时候,它会持续加速知道落到地面,然后经过几次反弹,最后停下来。如果用一张图来说明,它会如图10.5所示。

这可以起到作用,但效果并不是很好,到目前为止我们所完成的只是一个非常复杂的方式来使用线性缓冲复制cabasicanimation的行为。这种方式的好处在于我们可以更加精确地控制缓冲,这也意味着我们可以应用一个完全定制的缓冲函数。那么该如何做呢?

缓冲背后的数学并不很简单,但是幸运的是我们不需要一一实现它。罗伯特·彭纳有一个网页关于缓冲函数(http://www.robertpenner.com/easing ),包含了大多数普遍的缓冲函数的多种编程语言的实现的链接,包括c。这里是一个缓冲进入缓冲退出函数的示例(实际上有很多不同的方式去实现它)。

float quadraticeaseinout(float t) 
{
    return (t < 0.5)? (2 * t * t): (-2 * t * t) + (4 * t) - 1; 
}

 

对我们的弹性球来说,我们可以使用bounceeaseout函数:

float bounceeaseout(float t)
{
    if (t < 4/11.0) {
        return (121 * t * t)/16.0;
    } else if (t < 8/11.0) {
        return (363/40.0 * t * t) - (99/10.0 * t) + 17/5.0;
    } else if (t < 9/10.0) {
        return (4356/361.0 * t * t) - (35442/1805.0 * t) + 16061/1805.0;
    }
    return (54/5.0 * t * t) - (513/25.0 * t) + 268/25.0;
}

 

如果修改清单10.7的代码来引入bounceeaseout方法,我们的任务就是仅仅交换缓冲函数,现在就可以选择任意的缓冲类型创建动画了(见清单10.8)。

清单10.8 用关键帧实现自定义的缓冲函数

- (void)animate
{
    //reset ball to top of screen
    self.ballview.center = cgpointmake(150, 32);
    //set up animation parameters
    nsvalue *fromvalue = [nsvalue valuewithcgpoint:cgpointmake(150, 32)];
    nsvalue *tovalue = [nsvalue valuewithcgpoint:cgpointmake(150, 268)];
    cftimeinterval duration = 1.0;
    //generate keyframes
    nsinteger numframes = duration * 60;
    nsmutablearray *frames = [nsmutablearray array];
    for (int i = 0; i < numframes; i++) {
        float time = 1/(float)numframes * i;
        //apply easing
        time = bounceeaseout(time);
        //add keyframe
        [frames addobject:[self interpolatefromvalue:fromvalue tovalue:tovalue time:time]];
    }
    //create keyframe animation
    cakeyframeanimation *animation = [cakeyframeanimation animation];
    animation.keypath = @"position";
    animation.duration = 1.0;
    animation.delegate = self;
    animation.values = frames;
    //apply animation
    [self.ballview.layer addanimation:animation forkey:nil];
}

 

10.3 总结

在这一章中,我们了解了有关缓冲和camediatimingfunction类,它可以允许我们创建自定义的缓冲函数来完善我们的动画,同样了解了如何用cakeyframeanimation来避开camediatimingfunction的限制,创建完全自定义的缓冲函数。

在下一章中,我们将要研究基于定时器的动画--另一个给我们对动画更多控制的选择,并且实现对动画的实时操纵。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

  • ios uicollectionview实现横向滚动

    现在使用卡片效果的app很多,之前公司让实现一种卡片效果,就写了一篇关于实现卡片的文章。文章最后附有demo实现上我选择了使用uicollectionview ... [阅读全文]
  • iOS UICollectionView实现横向滑动

    本文实例为大家分享了ios uicollectionview实现横向滑动的具体代码,供大家参考,具体内容如下uicollectionview的横向滚动,目前我使... [阅读全文]
  • iOS13适配深色模式(Dark Mode)的实现

    iOS13适配深色模式(Dark Mode)的实现

    好像大概也许是一年前, mac os系统发布了深色模式外观, 看着挺刺激, 时至今日用着也还挺爽的终于, 随着iphone11等新手机的发售, ios 13系统... [阅读全文]
  • ios 使用xcode11 新建项目工程的步骤详解

    ios 使用xcode11 新建项目工程的步骤详解

    xcode11新建项目工程,新增了scenedelegate这个类,转而将原appdelegate负责的对ui生命周期的处理担子接了过来。故此可以理解为:ios... [阅读全文]
  • iOS实现转盘效果

    本文实例为大家分享了ios实现转盘效果的具体代码,供大家参考,具体内容如下demo下载地址: ios转盘效果功能:实现了常用的ios转盘效果,轮盘抽奖效果的实现... [阅读全文]
  • iOS开发实现转盘功能

    本文实例为大家分享了ios实现转盘功能的具体代码,供大家参考,具体内容如下今天给同学们讲解一下一个转盘选号的功能,直接上代码直接看viewcontroller#... [阅读全文]
  • iOS实现轮盘动态效果

    本文实例为大家分享了ios实现轮盘动态效果的具体代码,供大家参考,具体内容如下一个常用的绘图,主要用来打分之类的动画,效果如下。主要是ios的绘图和动画,本来想... [阅读全文]
  • iOS实现九宫格连线手势解锁

    本文实例为大家分享了ios实现九宫格连线手势解锁的具体代码,供大家参考,具体内容如下demo下载地址:效果图:核心代码://// clockview.m// 手... [阅读全文]
  • iOS实现卡片堆叠效果

    本文实例为大家分享了ios实现卡片堆叠效果的具体代码,供大家参考,具体内容如下如图,这就是最终效果。去年安卓5.0发布的时候,当我看到安卓全新的material... [阅读全文]
  • iOS利用余弦函数实现卡片浏览工具

    iOS利用余弦函数实现卡片浏览工具

    本文实例为大家分享了ios利用余弦函数实现卡片浏览工具的具体代码,供大家参考,具体内容如下一、实现效果通过拖拽屏幕实现卡片移动,左右两侧的卡片随着拖动变小,中间... [阅读全文]
验证码:
移动技术网