Xummer

使用 CATransaction flush设置cube动画的两个面

最近项目动画比较多,主要用到CATracnsactioncube动画。但是遇到个问题,举个例子来说:self.view一开始的背景颜色为灰色,在加cube动画之前设置self.view的背景为红色,会出现由灰色背景到红色背景的cube动画。如下图,

代码

[self.view setBackgroundColor:[UIColor redColor]];
CATransition *transition = [CATransition animation];

transition.type = @"alignedCube";
transition.subtype = kCATransitionFromTop;
transition.duration = 0.5;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.repeatCount = HUGE_VALF;
//    transition.repeatDuration = 1.0f
transition.delegate = self;
[self.view.layer addAnimation:transition forKey:@"transition"];

使用[CATransaction flush]

若在设置红色背景后加[CATransaction flush];就可以实现cube动画两个界面都是红色了。如图,

代码

[self.view setBackgroundColor:[UIColor redColor]];
[CATransaction flush];
CATransition *transition = [CATransition animation];

transition.type = @"alignedCube";
transition.subtype = kCATransitionFromTop;
transition.duration = 0.5;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.repeatCount = HUGE_VALF;
//    transition.repeatDuration = 1.0f
transition.delegate = self;
[self.view.layer addAnimation:transition forKey:@"transition"];

总结

CATransactioncube动画有一个缓存一样的机制,因为要显示两个viewlayer,若不加[CATransaction flush]则系统默认为在[self.view.layer addAnimation:transition forKey:@"transition"];之前的对view的操作全部作为动画的内容。addAnimation时从缓存中取出之前的viewlayer,作为cube中即将消失的一面,在将所有的改动后的viewlayer作为cube新的一面。[CATransaction flush]起到了分割线的作用。

 之前,存入缓存,作为cube中即将消失的一面
 ------------------------
  [CATransaction flush];
 之后,改动view直到addAnimation之前作为cube中新的一面
 ------------------------
  [self.view.layer addAnimation:transition forKey:@"transition"];