ios - CAShapeLayer 动画路径故障/闪烁(从椭圆到矩形再返回)

标签 ios core-animation cgpath cabasicanimation

当我创建显式动画以将 CAShapeLayer 的路径值从椭圆更改为矩形时,我遇到了问题。

在我的 Canvas Controller 中,我设置了一个基本的 CAShapeLayer 并将其添加到 Root View 的层:

CAShapeLayer *aLayer;
aLayer = [CAShapeLayer layer];
aLayer.frame = CGRectMake(100, 100, 100, 100);
aLayer.path = CGPathCreateWithEllipseInRect(aLayer.frame, nil);
aLayer.lineWidth = 10.0f;
aLayer.strokeColor = [UIColor blackColor].CGColor;
aLayer.fillColor = [UIColor clearColor].CGColor;
[self.view.layer addSublayer:aLayer];

然后,当我为路径设置动画时,当形状变为矩形时,在动画的最后几帧中出现奇怪的故障/闪烁,而在动画远离矩形时,在前几帧中出现奇怪的故障/闪烁。动画设置如下:

CGPathRef newPath = CGPathCreateWithRect(aLayer.frame, nil);
[CATransaction lock];
[CATransaction begin];
[CATransaction setAnimationDuration:5.0f];
CABasicAnimation *ba = [CABasicAnimation animationWithKeyPath:@"path"];
ba.autoreverses = YES;
ba.fillMode = kCAFillModeForwards;
ba.repeatCount = HUGE_VALF;
ba.fromValue = (id)aLayer.path;
ba.toValue = (__bridge id)newPath;
[aLayer addAnimation:ba forKey:@"animatePath"];
[CATransaction commit];
[CATransaction unlock];

我尝试了很多不同的事情,比如锁定/解锁 CATransaction,玩各种填充模式等......

这是故障图片: http://www.postfl.com/outgoing/renderingglitch.png

可以在这里找到我所经历的视频: http://vimeo.com/37720876

最佳答案

我收到了来自 quartz-dev 列表的反馈:

大卫邓肯写道:

Animating the path of a shape layer is only guaranteed to work when you are animating from like to like. A rectangle is a sequence of lines, while an ellipse is a sequence of arcs (you can see the sequence generated by using CGPathApply), and as such the animation between them isn't guaranteed to look very good, or work well at all.

To do this, you basically have to create an analog of a rectangle by using the same curves that you would use to create an ellipse, but with parameters that would cause the rendering to look like a rectangle. This shouldn't be too difficult (and again, you can use what you get from CGPathApply on the path created with CGPathAddEllipseInRect as a guide), but will likely require some tweaking to get right.

关于ios - CAShapeLayer 动画路径故障/闪烁(从椭圆到矩形再返回),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40103560/

相关文章:

iphone - 从 shoutcast iOS 编程获取元数据

iphone - 具有任意起点的圆形动画 View

iphone - 更改 UIView 的 CALayer 框架(self.view.layer.frame = ...)似乎没有效果

ios - 在可缩放的 UIView 中保留 CAShapeLayer 的 lineWidth

iphone - 尝试将 NSData 从 NSURLConnection 写入文件后的 SIGABRT(无法识别的选择器)

ios - 如何在 Swift 中向祖父 View Controller 发送消息

ios - 如何使用 NSNotificationCenter 自动更新列表项状态?

ios - 使用核心动画后如何获取 View 的当前旋转?

core-graphics - 在 CGPath 上获取随机 CGPoint

ios - CGPath 麻烦吗?