我试图将圆形变成正方形,反之亦然,目前已经接近成功。但是它没有预期的动画效果。我希望正方形的所有角落都能同时进行动画/变形,但我得到的只是以下内容:
我使用CAShapeLayer
和CABasicAnimation
来动画化形状属性。
这是我如何创建圆形路径的方法:
- (UIBezierPath *)circlePathWithCenter:(CGPoint)center radius:(CGFloat)radius
{
UIBezierPath *circlePath = [UIBezierPath bezierPath];
[circlePath addArcWithCenter:center radius:radius startAngle:0 endAngle:M_PI/2 clockwise:YES];
[circlePath addArcWithCenter:center radius:radius startAngle:M_PI/2 endAngle:M_PI clockwise:YES];
[circlePath addArcWithCenter:center radius:radius startAngle:M_PI endAngle:3*M_PI/2 clockwise:YES];
[circlePath addArcWithCenter:center radius:radius startAngle:3*M_PI/2 endAngle:M_PI clockwise:YES];
[circlePath closePath];
return circlePath;
}
这是一个正方形路径:
- (UIBezierPath *)squarePathWithCenter:(CGPoint)center size:(CGFloat)size
{
CGFloat startX = center.x-size/2;
CGFloat startY = center.y-size/2;
UIBezierPath *squarePath = [UIBezierPath bezierPath];
[squarePath moveToPoint:CGPointMake(startX, startY)];
[squarePath addLineToPoint:CGPointMake(startX+size, startY)];
[squarePath addLineToPoint:CGPointMake(startX+size, startY+size)];
[squarePath addLineToPoint:CGPointMake(startX, startY+size)];
[squarePath closePath];
return squarePath;
}
我将圆形路径应用于我的一个视图层,并设置填充等参数。它完美地绘制出来了。 然后,在我的gestureRecognizer选择器中,我创建并运行以下动画:
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"];
animation.duration = 1;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.fromValue = (__bridge id)(self.stateLayer.path);
animation.toValue = (__bridge id)(self.stopPath.CGPath);
self.stateLayer.path = self.stopPath.CGPath;
[self.stateLayer addAnimation:animation forKey:@"animatePath"];
正如您可以在 circlePathWithCenter:radius:
和 squarePathWithCenter:size:
中注意到的那样,我遵循了这里的建议(具有相同数量的线段和控制点):平滑形状转换动画
动画看起来比上面的帖子更好,但它仍然不是我想要实现的 :(
我知道我可以使用简单的 CALayer
,然后设置适当级别的 cornerRadius
将正方形/矩形变成圆形,之后通过动画 cornerRadius
属性将其从圆形变为正方形,但我仍然非常好奇是否可以使用 CAShapeLayer
和 path
动画来实现。
提前感谢您的帮助!