当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS开发之过渡

iOS开发之过渡

2018年10月14日  | 移动技术网IT编程  | 我要评论

小潘潘 孙鹏,刘秋实,他们生活的世界下载

过渡

有时候对于ios应用程序来说,希望能通过属性动画来对比较难做动画的布局进行一些改变。比如交换一段文本和图片,或者用一段网格视图来替换,等等。属性动画只对图层的可动画属性起作用,所以如果要改变一个不能动画的属性(比如图片),或者从层级关系中添加或者移除图层,属性动画将不起作用。

于是就有了过渡的概念。过渡并不像属性动画那样平滑地在两个值之间做动画,而是影响到整个图层的变化。过渡动画首先展示之前的图层外观,然后通过一个交换过渡到新的外观。

为了创建一个过渡动画,我们将使用catransition,同样是另一个caanimation的子类,和别的子类不同,catransition有一个type和subtype来标识变换效果。type属性是一个nsstring类型,可以被设置成如下类型:

kcatransitionfade 
kcatransitionmovein 
kcatransitionpush 
kcatransitionreveal

到目前为止你只能使用上述四种类型,但你可以通过一些别的方法来自定义过渡效果,后续会详细介绍。

默认的过渡类型是kcatransitionfade,当你在改变图层属性之后,就创建了一个平滑的淡入淡出效果。

默认的过渡类型是kcatransitionfade,当你在改变图层属性之后,就创建了一个平滑的淡入淡出效果。

我们在第七章的例子中就已经用到过kcatransitionpush,它创建了一个新的图层,从边缘的一侧滑动进来,把旧图层从另一侧推出去的效果。

kcatransitionmovein和kcatransitionreveal与kcatransitionpush类似,都实现了一个定向滑动的动画,但是有一些细微的不同,kcatransitionmovein从顶部滑动进入,但不像推送动画那样把老图层推走,然而kcatransitionreveal把原始的图层滑动出去来显示新的外观,而不是把新的图层滑动进入。

后面三种过渡类型都有一个默认的动画方向,它们都从左侧滑入,但是你可以通过subtype来控制它们的方向,提供了如下四种类型:

kcatransitionfromright 
kcatransitionfromleft 
kcatransitionfromtop 
kcatransitionfrombottom

一个简单的用catransition来对非动画属性做动画的例子如清单8.11所示,这里我们对uiimage的image属性做修改,但是隐式动画或者capropertyanimation都不能对它做动画,因为core animation不知道如何在插图图片。通过对图层应用一个淡入淡出的过渡,我们可以忽略它的内容来做平滑动画(图8.4),我们来尝试修改过渡的type常量来观察其它效果。

清单8.11 使用catransition来对uiimageview做动画

@interface viewcontroller ()

@property (nonatomic, weak) iboutlet uiimageview *imageview;
@property (nonatomic, copy) nsarray *images;

@end

@implementation viewcontroller

- (void)viewdidload
{
    [super viewdidload];
    //set up images
    self.images = @[[uiimage imagenamed:@"anchor.png"],
                    [uiimage imagenamed:@"cone.png"],
                    [uiimage imagenamed:@"igloo.png"],
                    [uiimage imagenamed:@"spaceship.png"]];
}


- (ibaction)switchimage
{
    //set up crossfade transition
    catransition *transition = [catransition animation];
    transition.type = kcatransitionfade;
    //apply transition to imageview backing layer
    [self.imageview.layer addanimation:transition forkey:nil];
    //cycle to next image
    uiimage *currentimage = self.imageview.image;
    nsuinteger index = [self.images indexofobject:currentimage];
    index = (index + 1) % [self.images count];
    self.imageview.image = self.images[index];
}

@end

你可以从代码中看出,过渡动画和之前的属性动画或者动画组添加到图层上的方式一致,都是通过-addanimation:forkey:方法。但是和属性动画不同的是,对指定的图层一次只能使用一次catransition,因此,无论你对动画的键设置什么值,过渡动画都会对它的键设置成“transition”,也就是常量kcatransition。

这里写图片描述

图8.4 使用catransition对图像平滑淡入淡出

隐式过渡

catransision可以对图层任何变化平滑过渡的事实使得它成为那些不好做动画的属性图层行为的理想候选。苹果当然意识到了这点,并且当设置了calayer的content属性的时候,catransition的确是默认的行为。但是对于视图关联的图层,或者是其他隐式动画的行为,这个特性依然是被禁用的,但是对于你自己创建的图层,这意味着对图层contents图片做的改动都会自动附上淡入淡出的动画。

我们在第七章使用catransition作为一个图层行为来改变图层的背景色,当然backgroundcolor属性可以通过正常的capropertyanimation来实现,但这不是说不可以用catransition来实行。

对图层树的动画

catransition并不作用于指定的图层属性,这就是说你可以在即使不能准确得知改变了什么的情况下对图层做动画,例如,在不知道uitableview哪一行被添加或者删除的情况下,直接就可以平滑地刷新它,或者在不知道uiviewcontroller内部的视图层级的情况下对两个不同的实例做过渡动画。

这些例子和我们之前所讨论的情况完全不同,因为它们不仅涉及到图层的属性,而且是整个图层树的改变–我们在这种动画的过程中手动在层级关系中添加或者移除图层。

这里用到了一个小诡计,要确保catransition添加到的图层在过渡动画发生时不会在树状结构中被移除,否则catransition将会和图层一起被移除。一般来说,你只需要将动画添加到被影响图层的superlayer。

在清单8.12中,我们展示了如何在uitabbarcontroller切换标签的时候添加淡入淡出的动画。这里我们建立了默认的标签应用程序模板,然后用uitabbarcontrollerdelegate的-tabbarcontroller:didselectviewcontroller:方法来应用过渡动画。我们把动画添加到uitabbarcontroller的视图图层上,于是在标签被替换的时候动画不会被移除。

清单8.12 对uitabbarcontroller做动画

#import "appdelegate.h"
#import "firstviewcontroller.h" 
#import "secondviewcontroller.h"
#import 
@implementation appdelegate
- (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions
{
    self.window = [[uiwindow alloc] initwithframe: [[uiscreen mainscreen] bounds]];
    uiviewcontroller *viewcontroller1 = [[firstviewcontroller alloc] init];
    uiviewcontroller *viewcontroller2 = [[secondviewcontroller alloc] init];
    self.tabbarcontroller = [[uitabbarcontroller alloc] init];
    self.tabbarcontroller.viewcontrollers = @[viewcontroller1, viewcontroller2];
    self.tabbarcontroller.delegate = self;
    self.window.rootviewcontroller = self.tabbarcontroller;
    [self.window makekeyandvisible];
    return yes;
}
- (void)tabbarcontroller:(uitabbarcontroller *)tabbarcontroller didselectviewcontroller:(uiviewcontroller *)viewcontroller
{
    ?//set up crossfade transition
    catransition *transition = [catransition animation];
    transition.type = kcatransitionfade;
    //apply transition to tab bar controller's view
    [self.tabbarcontroller.view.layer addanimation:transition forkey:nil];
}
@end

自定义动画

我们证实了过渡是一种对那些不太好做平滑动画属性的强大工具,但是catransition的提供的动画类型太少了。

更奇怪的是苹果通过uiview +transitionfromview:toview:duration:options:completion:和+transitionwithview:duration:options:animations:方法提供了core animation的过渡特性。但是这里的可用的过渡选项和catransition的type属性提供的常量完全不同。uiview过渡方法中options参数可以由如下常量指定:

uiviewanimationoptiontransitionflipfromleft 
uiviewanimationoptiontransitionflipfromright
uiviewanimationoptiontransitioncurlup 
uiviewanimationoptiontransitioncurldown
uiviewanimationoptiontransitioncrossdissolve 
uiviewanimationoptiontransitionflipfromtop 
uiviewanimationoptiontransitionflipfrombottom

除了uiviewanimationoptiontransitioncrossdissolve之外,剩下的值和catransition类型完全没关系。你可以用之前例子修改过的版本来测试一下(见清单8.13)。

清单8.13 使用uikit提供的方法来做过渡动画

@interface viewcontroller ()
@property (nonatomic, weak) iboutlet uiimageview *imageview;
@property (nonatomic, copy) nsarray *images;
@end
@implementation viewcontroller
- (void)viewdidload
{
    [super viewdidload]; //set up images
    self.images = @[[uiimage imagenamed:@"anchor.png"],
                    [uiimage imagenamed:@"cone.png"],
                    [uiimage imagenamed:@"igloo.png"],
                    [uiimage imagenamed:@"spaceship.png"]];
- (ibaction)switchimage
{
    [uiview transitionwithview:self.imageview duration:1.0
                       options:uiviewanimationoptiontransitionflipfromleft
                    animations:^{
                        //cycle to next image
                        uiimage *currentimage = self.imageview.image;
                        nsuinteger index = [self.images indexofobject:currentimage];
                        index = (index + 1) % [self.images count];
                        self.imageview.image = self.images[index];
                    }
                    completion:null];
}

@end

效果如下:

这里写图片描述

文档暗示过在ios5(带来了core image框架)之后,可以通过catransition的filter属性,用cifilter来创建其它的过渡效果。然而直到ios6都做不到这点。试图对catransition使用core image的滤镜完全没效果(但是在mac os中是可行的,也许文档是想表达这个意思)。

因此,根据要实现的效果,你只用关心是用catransition还是用uiview的过渡方法就可以了。希望下个版本的ios可以通过catransition很好的支持core image的过渡滤镜效果(或许甚至会有新的方法)。

但这并不意味着在ios上就不能实现自定义的过渡效果了。这只是意味着你需要做一些额外的工作。就像之前提到的那样,过渡动画做基础的原则就是对原始的图层外观截图,然后添加一段动画,平滑过渡到图层改变之后那个截图的效果。如果我们知道如何对图层截图,我们就可以使用属性动画来代替catransition或者是uikit的过渡方法来实现动画。

事实证明,对图层做截图还是很简单的。calayer有一个-renderincontext:方法,可以通过把它绘制到core graphics的上下文中捕获当前内容的图片,然后在另外的视图中显示出来。如果我们把这个截屏视图置于原始视图之上,就可以遮住真实视图的所有变化,于是重新创建了一个简单的过渡效果。

清单8.14演示了一个基本的实现。我们对当前视图状态截图,然后在我们改变原始视图的背景色的时候对截图快速转动并且淡出,图8.5展示了我们自定义的过渡效果。

为了让事情更简单,我们用uiview -animatewithduration:completion:方法来实现。虽然用cabasicanimation可以达到同样的效果,但是那样的话我们就需要对图层的变换和不透明属性创建单独的动画,然后当动画结束的时候在caanimationdelegate中把coverview从屏幕中移除。

清单8.14 用renderincontext:创建自定义过渡效果

@implementation viewcontroller
- (ibaction)performtransition
{
    //preserve the current view snapshot
    uigraphicsbeginimagecontextwithoptions(self.view.bounds.size, yes, 0.0);
    [self.view.layer renderincontext:uigraphicsgetcurrentcontext()];
    uiimage *coverimage = uigraphicsgetimagefromcurrentimagecontext();
    //insert snapshot view in front of this one
    uiview *coverview = [[uiimageview alloc] initwithimage:coverimage];
    coverview.frame = self.view.bounds;
    [self.view addsubview:coverview];
    //update the view (we'll simply randomize the layer background color)
    cgfloat red = arc4random() / (cgfloat)int_max;
    cgfloat green = arc4random() / (cgfloat)int_max;
    cgfloat blue = arc4random() / (cgfloat)int_max;
    self.view.backgroundcolor = [uicolor colorwithred:red green:green blue:blue alpha:1.0];
    //perform animation (anything you like)
    [uiview animatewithduration:1.0 animations:^{
        //scale, rotate and fade the view
        cgaffinetransform transform = cgaffinetransformmakescale(0.01, 0.01);
        transform = cgaffinetransformrotate(transform, m_pi_2);
        coverview.transform = transform;
        coverview.alpha = 0.0;
    } completion:^(bool finished) {
        //remove the cover view now we're finished with it
        [coverview removefromsuperview];
    }];
}
@end

这里写图片描述

图8.5 使用renderincontext:创建自定义过渡效果

这里有个警告:-renderincontext:捕获了图层的图片和子图层,但是不能对子图层正确地处理变换效果,而且对视频和opengl内容也不起作用。但是用catransition,或者用私有的截屏方式就没有这个限制了。

在动画过程中取消动画

之前提到过,你可以用-addanimation:forkey:方法中的key参数来在添加动画之后检索一个动画,使用如下方法:

- (caanimation *)animationforkey:(nsstring *)key;

但并不支持在动画运行过程中修改动画,所以这个方法主要用来检测动画的属性,或者判断它是否被添加到当前图层中。

为了终止一个指定的动画,你可以用如下方法把它从图层移除掉:

- (void)removeanimationforkey:(nsstring *)key;

或者移除所有动画:

- (void)removeallanimations;

动画一旦被移除,图层的外观就立刻更新到当前的模型图层的值。一般说来,动画在结束之后被自动移除,除非设置removedoncompletion为no,如果你设置动画在结束之后不被自动移除,那么当它不需要的时候你要手动移除它;否则它会一直存在于内存中,直到图层被销毁。

我们来扩展之前旋转飞船的示例,这里添加一个按钮来停止或者启动动画。这一次我们用一个非nil的值作为动画的键,以便之后可以移除它。-animationdidstop:finished:方法中的flag参数表明了动画是自然结束还是被打断,我们可以在控制台打印出来。如果你用停止按钮来终止动画,它会打印no,如果允许它完成,它会打印yes。

清单8.15是更新后的示例代码,图8.6显示了结果。

清单8.15 开始和停止一个动画

@interface viewcontroller ()

@property (nonatomic, weak) iboutlet uiview *containerview;
@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];
}

- (ibaction)start
{
    //animate the ship rotation
    cabasicanimation *animation = [cabasicanimation animation];
    animation.keypath = @"transform.rotation";
    animation.duration = 2.0;
    animation.byvalue = @(m_pi * 2);
    animation.delegate = self;
    [self.shiplayer addanimation:animation forkey:@"rotateanimation"];
}

- (ibaction)stop
{
    [self.shiplayer removeanimationforkey:@"rotateanimation"];
}

- (void)animationdidstop:(caanimation *)anim finished:(bool)flag
{
    //log that the animation stopped
    nslog(@"the animation stopped (finished: %@)", flag? @"yes": @"no");
}

@end

这里写图片描述

图8.6 通过开始和停止按钮控制的旋转动画

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

相关文章:

验证码:
移动技术网