【问题标题】:Core Animation Off-Screen to Onscreen Animation核心动画离屏到屏幕动画
【发布时间】:2012-05-29 00:26:11
【问题描述】:

在我正在制作的应用程序中,我试图让一个按钮在屏幕外启动并在屏幕上移动。我不知道如何从屏幕外的按钮开始,但我知道一旦我弄清楚了,我可以执行以下代码:

[UIView beginAnimation:@"animate" context: nil];
[UIView setAnimationDuration:3];
self.myButton.frame = CGRectMake (20, 100, 40, 80);
//Other animations
[UIView commitAnimations];

另外,在[UIView beginAnimation:@"animate" context:nil]; 行中,上下文参数是否要求CGContextRef?

【问题讨论】:

    标签: iphone objective-c ios core-animation core-graphics


    【解决方案1】:

    我假设您问的是如何让按钮从屏幕外动画到屏幕上,为此只需将按钮的原点位置设置为位于屏幕外的坐标。

    self.myButton.frame = CGRectMake(-80, 100, 40, 80);
    

    完成此操作后,您可以使用发布的代码在屏幕上制作动画。请记住,按钮将从第一个位置移动到第二个位置,这意味着如果您使用我使用的坐标,按钮将从左侧移动到屏幕上,而 y 位置不会改变。请记住,在 setAnimationDuration 中分配的时间内,您将按钮放置得越远,它必须移动到屏幕上的速度就越快。

    所以从左边动画到屏幕上

    self.myButton.frame = CGRectMake(-80, 100, 40, 80);
    // begin animation block    
    [UIView beginAnimations:@"animate" context: nil];
    [UIView setAnimationDuration:3];
    self.myButton.frame = CGRectMake (20, 100, 40, 80);
    // commit frame changes to be animated
    [UIView commitAnimations];
    

    此外,如果按钮之前在屏幕上,它似乎会从屏幕上传送出去,然后在使用该代码时滑回。

    哦,要回答您关于上下文的问题,不,它不必是 CGContextRef,它可以是任何数据类型(只要它是对象而不是原语)。它基本上是动画发生时传递给委托的数据。

    【讨论】:

      【解决方案2】:

      BeginAnimation:context: 在 iOS 4.0 或更高版本中不鼓励使用,您应该使用基于块的方法之一。您应该设置原始帧,使其不在屏幕上。这是一个稍微延迟后将按钮从右侧移入的示例:

      self.myButton.frame = CGRectMake (340, 250, 40, 80);
          [self.view addSubview:myButton];
          [UIView animateWithDuration:5 delay:.2 options: UIViewAnimationOptionLayoutSubviews animations:^{
          self.myButton.frame = CGRectMake (140, 250, 40, 80);
          //Other animations
          }
           completion:nil];
      

      【讨论】:

      • 我编译了该代码并添加了“self.myButton.frame = [UIColor redColor];”只是这样我就可以看到模拟器中没有发生任何事情的结果。你知道出了什么问题吗?还有,为什么不鼓励“beginAnimation:context:”?谢谢
      • 设置颜色,不想用frame,用self.myButton.backgroundColor = [UIColor redColor];但是,我不认为设置颜色是可动画的。至于为什么不鼓励它,我不知道——这是 Apple 在其文档中所说的。
      【解决方案3】:

      如果你没有使用 xibs,你可以在viewDidLoad 中设置按钮的框架离屏(如果你使用的是 xibs,请将其滑出视图):

       //create the button or get it from the xib
       CGRect rect = self.myButton.frame;
       rect.origin.x=-200;//or a good point to hide the button
       self.myButton.frame=rect;
      

      那么当你想为按钮设置动画时,你可以使用块动画:

       [UIView animateWithDuration:0.3f delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
              self.myButton.frame=SET_YOUR_FRAME;
          } completion:^(BOOL finished)];
      

      有关上下文,请参阅documentation

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-18
        相关资源
        最近更新 更多