在核心动画中,红框代替 UIImage 视图移动

Posted

技术标签:

【中文标题】在核心动画中,红框代替 UIImage 视图移动【英文标题】:Red Box Moving in Place of UIImage View in Core Animation 【发布时间】:2013-02-11 01:56:16 【问题描述】:

我的第一个核心动画只是一个从 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"];

【问题讨论】:

花点时间再次阅读您的代码。它正在做你所要求的。为什么一开始就吃掉你创建红色层? 【参考方案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

【讨论】:

我非常了解 UIView 动画,我正在尝试制作更复杂的动画,所以我搬到了 CA。感谢您的帮助!

以上是关于在核心动画中,红框代替 UIImage 视图移动的主要内容,如果未能解决你的问题,请参考以下文章

使用核心动画在屏幕上移动 UIImage

在 UIView 中动画图像

UIImage 视图从一个图像动画到下一个图像

UIImage 从一个 UIImageView 移动到另一个 UIImageView 的动画

iOS 为视图设置模糊动画

把 UIView 变成 UIImage