2015-11-13 45 views
2

我有一個圓形的CAShapeLayer,我想爲其填充動畫。我創建了我CAShapeLayer作爲如何動畫CAShapeLayer的填充?

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    // Filled layer 
    CAShapeLayer *filledCircleShape = [CAShapeLayer new]; 
    filledCircleShape.frame = CGRectMake(100, 100, 100, 100); 
    filledCircleShape.fillColor = [UIColor purpleColor].CGColor; 
    filledCircleShape.strokeColor = [UIColor grayColor].CGColor; 
    filledCircleShape.lineWidth = 2; 
    filledCircleShape.path = [self filledBezierPathWithRelativeFill:.75 inFrame:filledCircleShape.frame].CGPath; 
    [self.view.layer addSublayer:filledCircleShape]; 

    self.filleShapeLayer = filledCircleShape; 
} 

- (UIBezierPath *)filledBezierPathWithRelativeFill:(CGFloat)relativeFill 
{ 
    UIBezierPath *filledCircleArc = [UIBezierPath bezierPath]; 
    CGFloat arcAngle = 2 * acos(1 - 2 * relativeFill); // 2arccos ((r - 2rp)/r) == 2 arccos(1 - 2p) 
    CGFloat startAngle = (M_PI - arcAngle)/2; 
    CGFloat endAngle = startAngle + arcAngle; 
    [filledCircleArc addArcWithCenter:self.boundsCenter radius:self.radius startAngle:startAngle endAngle:endAngle clockwise:YES]; 

    return filledCircleArc; 
} 

這看起來是這樣的: enter image description here

我曾嘗試以下,使其動畫路徑的變化。

- (void)animate 
{ 
    UIBezierPath *toBezierPath = [self filledBezierPathWithRelativeFill:0.3 inFrame:CGRectMake(100, 100, 100, 100)]; 
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"path"]; 
    pathAnimation.duration = 5.f; 
    pathAnimation.toValue = (__bridge id)toBezierPath.CGPath; 
    [self.filleShapeLayer addAnimation:pathAnimation forKey:@"path"]; 
} 

哪種作品。形狀圖層動畫,但是看起來像這樣

enter image description here

enter image description here

我想要的形狀層動畫就像一個沙漏,起始於一個百分比,然後動畫下來的。

任何有關如何使用CAShapeLayer實現此目的的想法?

回答

1

CAShapeLayer是填補的矯枉過正。這不是神奇地以你想要的方式動畫,反正也沒有必要。從一個大的方形紫色視圖開始,並將其向下移動 - 但放置一個遮罩,以便只有形狀區域的內部可見 - 正如我在此處所做的(除了我正在填充而不是清空):

enter image description here

+0

我想到了這一點,這當然是最簡單的解決方案,但因爲這只是一個操場項目,我想看看是否有可能得到與形狀圖層相同的結果。是嗎? :S(「我們不這樣做,因爲它很容易,我們這樣做是因爲它很難。」) – Groot

+0

一個問題是形狀不閉合。 – matt