如何为UIBezierPath设置动画

时间:2012-06-03 10:20:57

标签: objective-c animation calayer cgpath uibezierpath

我想将矩形的UIBezierPath设置为三角形的动画,而不是为路径上的视图设置动画,而是为路径本身设置动画,使其从一种形状变为另一种形状。路径被添加到CALayer

CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.fillColor = [[UIColor whiteColor] CGColor];    
maskLayer.path = [self getRectPath];

-(CGPathRef)getTrianglePath
{
    UIBezierPath* triangle = [UIBezierPath bezierPath];
    [triangle moveToPoint:CGPointZero];
    [triangle addLineToPoint:CGPointMake(width(self.view),0)];
    [triangle addLineToPoint:CGPointMake(0, height(self.view))];
    [triangle closePath];
    return [triangle CGPath];
}

-(CGPathRef)getRectPath
{
    UIBezierPath*rect = [UIBezierPath bezierPathWithRect:self.view.frame];
    return [rect CGPath];
}

1 个答案:

答案 0 :(得分:30)

我不是CoreAnimation的专家,但您可以按如下方式定义CABasicAnimation

CABasicAnimation *morph = [CABasicAnimation animationWithKeyPath:@"path"];
morph.duration = 5;
morph.toValue = (id) [self getTrianglePath];
[maskLayer addAnimation:morph forKey:nil];

第一行声明您要定义一个更改图层path属性的动画。第二行表示动画需要五秒钟,第三行表示动画的最终状态。最后,我们将动画添加到图层。键是动画的唯一标识符,也就是说,如果使用相同的键添加两个动画,则仅考虑最后一个动画。此键还可用于覆盖所谓的隐式动画。默认情况下,CALayer有几个属性是动画的。更准确地说,如果您更改其中一个属性,则更改将以0.25的持续时间进行动画处理。

相关问题