如何在单个动画中缩放和旋转视图



我试图通过使视图从屏幕中心出现,同时增长到其全尺寸,同时以3D方式围绕x轴旋转来呈现视图。当我创建视图时,我对其应用变换,以确保它在开始时收缩和旋转(它太小了,实际上看不见),然后我尝试使用CATransform3D,如下所示:

CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform"];
CATransform3D transform = CATransform3DRotate(view.layer.transform, M_PI, 1.0, 0, 0);
transform = CATransform3DScale(transform, 1000, 1000, 1000);
transform.m34 = 1.0 / 10000;
[anim setToValue:[NSValue valueWithCATransform3D:transform]];
[anim setDuration:0.75f];
anim.removedOnCompletion = NO;
anim.delegate = self;
[view.layer addAnimation:anim forKey:@"grow"];

然而,这个动画并没有改变层的实际变换,所以我也这样做:

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
    view.layer.transform = CATransform3DIdentity;
    [view.layer removeAllAnimations];
}

以在动画停止后设置变换。然而,这有时会导致动画结束时出现明显的闪烁。我相信这是因为动画将原始变换放回动画阶段的末尾,而这发生在调用animationDidStop例程之前。有更好的方法吗?

编辑:将其合并到UIView动画中,可以通过这种方式直接设置变换:

view.layer.transform = CATransform3DScale(CATransform3DIdentity, 0.001, 0.001, 0.001);
view.layer.transform = CATransform3DRotate(view.layer.transform, M_PI, 1.0, 0.0, 0.0);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.75];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
CATransform3D transform = CATransform3DRotate(view.layer.transform, M_PI, 1.0, 0, 0);
transform = CATransform3DScale(rotationTransform, 1000, 1000, 1000);
transform.m34 = 1.0 / -500;
view.layer.transform = transform;
[UIView commitAnimations];

然而,我仍然希望能回答我最初的问题,即如何使用CAAnimation成功地实现同样的效果,因为这为动画提供了更大的灵活性。

编辑2:我最初的问题(如何用CAAnimation解决问题)的答案似乎非常简单。为了保持结束状态(并消除闪烁),我只需要添加以下行:

anim.fillMode = kCAFillModeForwards;

这可能会对您有所帮助:

  animationView.layer.anchorPoint = CGPointMake(0.0f, 0.0f);
  animationView.center = CGPointMake(0, 
                                  (animationView.center.y - 
                                   (animationView.bounds.size.height/2.0f)));
  // start the Page Open
  [UIView beginAnimations:@"Animation" context:nil];
  [UIView setAnimationDuration:2.0];     
  // set angle as per requirement
  [animationView.layer setValue:[NSNumber numberWithInt:180] 
                  forKeyPath:@"transform.rotation.x"];
  [UIView commitAnimations];

我知道这不是一个你可能希望得到的简洁明了的答案:)

但是在这里(UIView动画教程:实用食谱)你可以找到一个可下载的例子,它还展示了如何进行scale&旋转

如果运行示例,单击HUD,然后单击停止,则可以看到缩放和旋转。

请参阅关于iPad应用商店如何旋转和缩放的帖子,以获得答案和代码:如何像iOS 7 iPad应用商店一样同时翻转和放大UI查看它?

最新更新