【问题标题】:Smooth shape shift animation平滑的变形动画
【发布时间】:2013-06-30 01:39:33
【问题描述】:

如何改变形状(从椭圆形到矩形,反之亦然)动画?

脏代码:

UIBezierPath *roundedRectBezierPath = [UIBezierPath bezierPathWithRoundedRect:newRect cornerRadius:10];
UIBezierPath *ovalBezierPath = [UIBezierPath bezierPathWithOvalInRect:newRect];

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"];
animation.duration = 3;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

if (isRect) {

    self.shapeLayer.path = roundedRectBezierPath.CGPath;
    animation.fromValue = (__bridge id)(ovalBezierPath.CGPath);
    animation.toValue = (__bridge id)(roundedRectBezierPath.CGPath);

} else {

    self.shapeLayer.path = ovalBezierPath.CGPath;
    animation.fromValue = (__bridge id)(roundedRectBezierPath.CGPath);
    animation.toValue = (__bridge id)(ovalBezierPath.CGPath);

}    

[self.shapeLayer addAnimation:animation forKey:@"animatePath"];

结果很奇怪:

我希望形状会缩小/扩大,而不是奇怪的重绘。

【问题讨论】:

  • 哈哈!看起来矩形正在绘制[左上,右上,右下,左下],但椭圆是从“3点钟”位置逆时针绘制的。动画将映射从正方形到圆形的路径上的点。即矩形的左上角在圆圈上向右。尝试将圆形路径逆时针旋转 (4 * PI) / 3 rads。
  • 仍然不是预期的动画。
  • @user620297 相反。我期待这种行为。来自文档:“如果两条路径具有不同数量的控制点或段,则结果未定义”。
  • @DavidRönnqvist 你是对的。那么该怎么做呢?

标签: iphone ios cocoa-touch core-animation


【解决方案1】:

如果您查看文档,这正是您应该期待的行为。来自文档:

如果两条路径具有不同数量的控制点或线段,则结果未定义。

您可以通过两种方式解决此问题:

  • 自行创建路径,确保它们具有相同数量的路径
  • 自己为路径转换创建自定义动画。

创建具有相同数量的段和控制点的路径

对于第一个选项,我会使用 addArcWithCenter:radius:startAngle:endAngle:clockwise: 四次来组成圆角矩形。 (它会自动将直线添加到您的路径中)。您可以在"Thinking like Bézier paths"(由我编写)中阅读有关贝塞尔路径构造的更多信息。那里有一些交互式元素可以帮助您了解如何将弧线添加到路径中。

创建自定义路径动画

另一种选择是使用不同数量的控制点和/或线段以任何方式创建路径,并自己制作动画。 This is an excellent explanation 如何使用形状图层制作自己的路径动画。

【讨论】:

  • 两年多后,这个答案仍然有帮助。这个答案的最佳部分:“以一种可以保证它们都具有相同数量的路径的方式自己创建路径。”就我而言,我将椭圆更改为具有适当cornerRadius 的圆角矩形。动画现在完美运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-17
  • 2018-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多