0

我的第一个核心动画只是一个从 a 点移动到 b 点的图像。出于某种原因,当动画被调用时,会出现一个红色框并在我的图像的位置移动,而它只是坐在那里。这是我的代码:

-(IBAction)preform:(id)sender{
CALayer *layer = [CALayer layer];
[layer setPosition:CGPointMake(100.0, 100.0)];
[layer setBounds:CGRectMake(0.0, 0.0, 50.0, 60.0)];
[layer setBackgroundColor:[[UIColor redColor] CGColor]];
[imView.layer addSublayer:layer];

CGPoint point = CGPointMake(imView.frame.origin.x, imView.frame.origin.y);
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"];
anim.fromValue  = [NSValue valueWithCGPoint:point];
anim.toValue    = [NSValue valueWithCGPoint:CGPointMake(point.x + 50, point.y)];
anim.duration   = 1.5f;
anim.repeatCount =1;
anim.removedOnCompletion = YES;
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
[layer  addAnimation:anim forKey:@"position"];
}
4

1 回答 1

1

如果您的应用程序 UI 不需要那个红色框,请不要创建它,而是将动画应用到视图层。如果您确实需要那个红框,请创建,但将动画应用于视图层,而不是红框层

另请注意,除非您更改图层的anchorPoint,否则该position属性实际上是图层的中心,而不是角落。您需要考虑到这一点才能制作流畅的动画。

最后,如果您不希望在动画完成后视图回弹,则需要设置它的新位置。不用担心,在播放动画时,视图的重定位是不可见的。

建议的(和未经测试的)代码:

-(IBAction)preform:(id)sender{

  CGPoint point = CGPointMake(imView.frame.size.width/2.0 , imView.frame.size.height/2.0 );
  CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"];
  anim.fromValue  = [NSValue valueWithCGPoint:point];
  anim.toValue    = [NSValue valueWithCGPoint:CGPointMake(point.x + 50, point.y)];
  anim.duration   = 1.5f;
  anim.repeatCount =1;
  anim.removedOnCompletion = YES;
  anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
  [imView.layer  addAnimation:anim forKey:@"position"];

  imView.center = CGPointMake( imView.center.x + 50, imView.center.y
}

如果您改用动画辅助函数,这一切都会更容易UIView,但我认为您正在尝试学习如何使用CAAnimation

于 2013-02-11T02:33:41.520 回答