ios - 如何为CGPath的绘图部分制作动画

标签 ios objective-c core-animation cashapelayer cgpath

我想处理以下情况:

enter image description here

如果我使用CGBezierPath和CAShapeLayer绘制矩形,如下所示:

    CAShapeLayer *layerX = [CAShapeLayer layer];
    layerX.path = path.CGPath;

    layerX.lineWidth   = 3;
    layerX.strokeColor = [[UIColor whiteColor] CGColor];
    layerX.fillColor   = [[UIColor clearColor] CGColor];

    [self.view.layer addSublayer: layerX];

而且我想添加动画,例如附加的图像,该空白区域会在矩形路径周围不断移动,从而使矩形的视觉效果不断出现。 [旧蛇游戏中的蛇运动]

我尝试使用CABasicAnimation制作动画,但实际上我什么都做不了,谢谢。

最佳答案

尝试使用此代码可能会有所帮助。

    UIBezierPath *drawablePath = [UIBezierPath bezierPathWithRect:CGRectMake(100.0, 100.0, 150.0, 100.0)];
    CAShapeLayer *squareLayer = [[CAShapeLayer alloc] init];
    squareLayer.path = drawablePath.CGPath;
    squareLayer.strokeColor = [UIColor redColor].CGColor;
    squareLayer.lineWidth = 5.f;
    squareLayer.fillColor = [UIColor clearColor].CGColor;
    squareLayer.strokeEnd = 1.f;
    //squareLayer.strokeEnd = 0.9; // this line use draw half line but some animation issue.
    [self.view.layer addSublayer:squareLayer];

    CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    drawAnimation.fromValue = (id)[NSNumber numberWithFloat:0.10];
    drawAnimation.toValue = (id)[NSNumber numberWithFloat:1.f];
    drawAnimation.duration = 5.f;
    drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    [squareLayer addAnimation:drawAnimation forKey:@"drawRectStroke"];

此代码用于绘制带有动画的矩形。

关于ios - 如何为CGPath的绘图部分制作动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46212723/

相关文章:

ios - UICollectionView:页面控件的当前索引路径

ios - 将 RxSwift 链接到命令行工具的正确方法

ios - 如何从 UITextView 中删除垂直线并在 DALinedTextView 中从左侧键入文本?

ios - 根据它使用的 UITableViewCell 类型更改 heightForRowAtIndexPath?

ios - 使用延迟动画暂停 CALayer 动画

ios - 使用 ffmpeg 将 Mp4 转为 HLS

ios - 在 XCode Playgrounds 中注册单元重用标识符

ios - UITableView - 如何动态更新自调整大小单元格的框架

ios - 动画 : how to animate a view using layer?

ios - CAMediaTiming中的kCAFillModeRemoved和CAAnimation的removedOnCompletion属性之间的区别