ios - 在 for 循环中更改 CAShapeLayer 的路径无效

标签 ios objective-c animation cashapelayer cgpath

我在 for 循环中改变 <​​strong>CAShapeLayer 的路径,但它只显示循环的最后结果。我知道,我可以用 CABasicAnimation 做到这一点,但我需要以这种方式改变路径。有什么想法吗?

UIBezierPath *path = [ShapeManager getCirclePathAppendedWithCirclePathWithRadius:radius
                                                                        andFrame:self.view.bounds];
self.layer.fillRule = kCAFillRuleEvenOdd;
self.layer.fillColor = [UIColor grayColor].CGColor;
self.layer.opacity = 0.5;
self.layer.path = path.CGPath;
[self.view.layer addSublayer:self.layer];
for (int i = 1; i < 100; ++i) {
    path = [ShapeManager getCirclePathAppendedWithCirclePathWithRadius:self.view.bounds.size.width-i
                                                              andFrame:self.view.bounds];
    self.layer.path = path.CGPath;
}

辅助方法

+ (UIBezierPath *)getCirclePathAppendedWithCirclePathWithRadius:(CGFloat)radius andFrame:(CGRect)frame {
    UIBezierPath *backgroundPath = [UIBezierPath bezierPathWithRect:frame];
    [backgroundPath appendPath:[self getCirclePathWithRadius:radius andFrame:frame]];
    return backgroundPath;
}

+ (UIBezierPath *)getCirclePathWithRadius:(CGFloat)radius andFrame:(CGRect)frame {
    CGRect rect = frame;
    UIBezierPath *circlePath;
    circlePath = [UIBezierPath bezierPathWithArcCenter:(CGPoint){rect.size.width/2, rect.size.height/2} radius:radius startAngle:0 endAngle:M_PI*2 clockwise:YES];
    return circlePath;
}

最佳答案

您对使用 CABasicAnimation 的看法是正确的。

  1. 删除您的for 循环,它不会完成这项工作。
  2. path 键添加 CABasicAnimation,并在其中插入值。这段代码只能在 viewDidLoad 方法中调用一次:

UIBezierPath *fromPath = [self.class getCirclePathAppendedWithCirclePathWithRadius:self.view.bounds.size.width andFrame:self.view.bounds];
UIBezierPath *toPath = [self.class getCirclePathAppendedWithCirclePathWithRadius:self.view.bounds.size.width-99 andFrame:self.view.bounds];

CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath:@"path"];
animation.fromValue = (id)fromPath.CGPath;
animation.toValue = (id)toPath.CGPath;
animation.duration = 1; 

[layer addAnimation:animation forKey:@"pathAnimation"];
layer.speed = 0;

更新:

  1. 在最后一行中,您将 speed 值设置为 0,因为您将手动设置动画进度:

@property (nonatomic, assign) double progress;

- (void) setProgress: (double) progress {
    _progress = progress;        
    layer.timeOffset = (CFTimeInterval)progress; 
}

这假设动画持续时间为 1.0。否则你需要设置

layer.timeOffset = (CFTimeInterval)(progress * totalDuration);

现在根据更新的值在运动回调中设置进度即可。

关于ios - 在 for 循环中更改 CAShapeLayer 的路径无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40030317/

相关文章:

ios - 如何在 Swift 中禁用第三方键盘?

iphone - 使用 NSMutableSet 时出错

javascript - AngularJS 动画中的完成回调

Ubuntu 自动隐藏滚动条的 Jquery 版本?

javascript - Swift 等待 UIWebView 中 javascript 的页面加载

iphone - ios UIActivityViewController不附加发送短信的图像

iphone - 在 MapView 上点击注释时隐藏弹出窗口

objective-c - 检测鼠标右键单击 cocoa

objective-c - 初始化作为 C 数组的 Objective-C 类 ivar

javascript - 帮助这个动画循环