CABasicAnimation与CALayer路径不生成动画
我正在尝试将CALayer从正常转角过渡到圆角。我只想绕顶角,所以我使用的是UIBezier路径。这里是代码:CABasicAnimation与CALayer路径不生成动画
UIRectCorner corners = UIRectCornerTopLeft | UIRectCornerTopRight;
UIBezierPath* newPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(8.0f, 8.0f)];
UIBezierPath* oldPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(0.0f, 0.0f)];
CAShapeLayer* layer = [CAShapeLayer layer];
layer.frame = self.bounds;
layer.path = oldPath.CGPath;
self.layer.mask = layer;
CABasicAnimation* a = [CABasicAnimation animationWithKeyPath:@"path"];
[a setDuration:0.4f];
[a setFromValue:(id)layer.path];
[a setToValue:(id)newPath.CGPath];
layer.path = newPath.CGPath;
[layer addAnimation:a forKey:@"path"];
但是,当我运行这个,角是圆角,但没有动画 - 它会立即发生。我在这里看到了一些类似的问题,但他们没有解决我的问题。
Animating CALayer's shadowPath property
我敢肯定,我只是在做一个小东西错了,这是造成问题,但对我的生活,我不能弄明白。
解决方案:
- (void)roundCornersAnimated:(BOOL)animated {
UIRectCorner corners = UIRectCornerTopLeft | UIRectCornerTopRight;
UIBezierPath* newPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(8.0f, 8.0f)];
UIBezierPath* oldPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(0.0001f, 0.0001f)];
CAShapeLayer* layer = [CAShapeLayer layer];
layer.frame = self.bounds;
self.layer.mask = layer;
if(animated) {
CABasicAnimation* a = [CABasicAnimation animationWithKeyPath:@"path"];
[a setDuration:0.4f];
[a setFromValue:(id)oldPath.CGPath];
[a setToValue:(id)newPath.CGPath];
layer.path = newPath.CGPath;
[layer addAnimation:a forKey:@"path"];
} else {
layer.path = newPath.CGPath;
}
}
真的所有我需要做的是设置“从”值适当的动画。
它看起来像我在创建一个没有路径的形状图层,然后尝试为其添加路径的动画。形状图层是特殊情况,并不会以这种方式工作。
您必须在动画之前和之后的形状图层中有一个路径,并且该路径需要在其之前和之后具有相同数量的点。
您将需要创建一个圆角矩形路径,其中角半径为0(手动,使用一系列边和角弧),然后为要旋转的角建立一个非零半径的新路径,将该路径安装为动画。尽管如此,因为路径中需要的点数完全相同,并且我怀疑圆弧在半径为零时会简化为点。
我刚刚找到一个UIBezierPath调用,它将创建一个矩形,您可以在其中选择要绕过哪些角。该调用是bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:
这将创建一个矩形,只要你喜欢多少个圆角。但是,我不确定它是否适用于路径动画。您可能需要请求将所有拐角圆化,将2个非圆角设置为零半径。这样你可能会得到一个具有相同数量的点的路径作为圆角矩形路径,所以路径动画可以正常工作。你必须尝试一下。
感谢。你是对的。为动画设置一个正确的“from”值。 – 2012-07-13 14:34:52
尝试把:
layer.path = newPath.CGPath;
后:
[layer addAnimation:a forKey:@"path"];
解决办法是作为一个答案,而不是问题的一部分不错的,但是这是有帮助的反正这么+1 :) – buildsucceeded 2016-03-11 13:07:36