核心动画:离屏渲染与屏幕渲染动画

3
在我正在制作的应用程序中,我试图让一个按钮从屏幕外移动到屏幕上。我不确定如何使按钮在屏幕外开始移动,但我知道一旦我解决了这个问题,我可以使用下面的代码实现:
[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];中,context参数是否要求CGContextRef?
3个回答

5
我猜您是在问如何让按钮从屏幕外动画到屏幕上,只需将按钮的原点位置设置为位于屏幕外的坐标即可实现。
self.myButton.frame = CGRectMake(-80, 100, 40, 80);

一旦您完成这个步骤,您就可以使用您发布的代码将按钮动画显示在屏幕上。请注意,按钮将从第一个位置移动到第二个位置,这意味着如果您使用了我用过的坐标,该按钮将从左侧移动到屏幕上,而不会更改y方向的位置。请记住,您将按钮置于屏幕之外的距离越远,它就需要以更快的速度在设置的动画持续时间内移动到屏幕上。

因此,从左侧动画显示在屏幕上

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,它可以是任何数据类型(只要它是对象而不是基本类型)。它基本上是在动画发生时传递给委托的数据。

3

在iOS 4.0及以上版本中,不推荐使用BeginAnimation:context:方法,应该使用基于块的方法之一。您应该设置原始框架,使其脱离屏幕。以下是一个示例,在稍微延迟后从右侧移入按钮:

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:” 为什么被不推荐使用?谢谢。 - pasawaya
要设置颜色,您不想使用frame,而是使用self.myButton.backgroundColor = [UIColor redColor]; 但是,我认为设置颜色不可动画化。至于为什么不建议使用,我不知道——这是苹果在其文档中说的。 - rdelmar

2

如果您没有使用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)];

For the context see the documentation


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接