【问题标题】:What's the easiest way to animate a line?为线条制作动画最简单的方法是什么?
【发布时间】:2011-07-21 08:22:58
【问题描述】:

我正在创建一个应用程序,该应用程序涉及随着时间的推移在工作区中对线条进行动画处理。我目前的方法是在drawRect 中使用这样的代码:

CGContextSetStrokeColor(context, black);
CGContextBeginPath(context);
CGContextMoveToPoint(context, startPoint.x, startPoint.y);
CGContextAddLineToPoint(context, finalPoint.x, finalPoint.y);
CGContextStrokePath(context);

...然后只需设置一个计时器以每 0.05 秒运行一次以更新 finalPoint 并调用 setNeedsDisplay

我发现这种方法(当有 5 条线同时移动时)会严重减慢应用程序的速度,即使刷新频率如此之高,仍然显得生涩。

必须有一些更好的方法来在动画线条中执行这个非常简单的线条绘制 - 即说我想要一条线从 x1, y1 开始并在给定的时间长度内延伸到 x2, y2。我有什么选择?我需要让它执行得更快,并且很想摆脱这个笨重的计时器。

谢谢!

【问题讨论】:

    标签: objective-c ios ipad animation core-animation


    【解决方案1】:

    使用 CAShapeLayers,以及 CATransactions 和 CABasicAnimation 的组合。

    您可以将给定的路径添加到 shapeLayer 并让它进行渲染。

    一个 CAShapeLayer 对象有两个属性,称为strokeStartstrokeEnd,它们定义了线的末端应该沿着路径渲染的位置。 strokeStart 的默认值为 0.0,strokeEnd 的默认值为 1.0。

    如果您将路径设置为 strokeEnd 最初从 0.0 开始,您将看不到任何行。

    然后,您可以将strokeEnd 属性的动画从 0.0 设置为 1.0,您会看到线条变长了。

    要更改 CAShapeLayer 的隐式 0.25s 默认动画时间,可以在类中添加一个函数,如下所示:

    -(void)animateStrokeEnd:(CGFloat)_strokeEnd {
        [CATransaction begin];
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:keyPath];
        animation.duration = 2.0f; //or however long you want it to happen
        animation.fromValue = [NSNumber numberWithFloat:self.strokeEnd]; // from the current strokeEnd value
        animation.toValue = [NSNumber numberWithFloat:_strokeEnd]; //to the end of the path
        [CATransaction setCompletionBlock:^{ self.strokeEnd = _strokeEnd }];
        [self addAnimation:animation forKey:@"animateStrokeEnd"];
        [CATransaction commit];
    }
    

    您可以将 0.0f 到 1.0f 之间的任何值作为_strokeEnd 的值传递。

    setCompletionBlock: 确保您传递的值在动画完成后显式设置。

    【讨论】:

      猜你喜欢
      • 2010-11-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多