2012-07-13 68 views
17

我正在嘗試將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"]; 

但是,當我運行這個,角是圓角,但沒有動畫 - 它會立即發生。我在這裏看到了一些類似的問題,但他們沒有解決我的問題。

iPhone CALayer animation

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; 
    } 
} 

真的所有我需要做的是設置「從」值適當的動畫。

+1

解決辦法是作爲一個答案,而不是問題的一部分不錯的,但是這是有幫助的反正這麼+1 :) – buildsucceeded 2016-03-11 13:07:36

回答

10

它看起來像我在創建一個沒有路徑的形狀圖層,然後嘗試爲其添加路徑的動畫。形狀圖層是特殊情況,並不會以這種方式工作。

您必須在動畫之前和之後的形狀圖層中有一個路徑,並且該路徑需要在其之前和之後具有相同數量的點。

您將需要創建一個圓角矩形路徑,其中角半徑爲0(手動,使用一系列邊和角弧),然後爲要旋轉的角建立一個非零半徑的新路徑,將該路徑安裝爲動畫。儘管如此,因爲路徑中需要的點數完全相同,並且我懷疑圓弧在半徑爲零時會簡化爲點。

我剛剛找到一個UIBezierPath調用,它將創建一個矩形,您可以在其中選擇要繞過哪些角。該調用是bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:

這將創建一個矩形,只要你喜歡多少個圓角。但是,我不確定它是否適用於路徑動畫。您可能需要請求將所有拐角圓化,將2個非圓角設置爲零半徑。這樣你可能會得到一個具有相同數量的點的路徑作爲圓角矩形路徑,所以路徑動畫可以正常工作。你必須嘗試一下。

+0

感謝。你是對的。爲動畫設置一個正確的「from」值。 – 2012-07-13 14:34:52

4

嘗試把:

layer.path = newPath.CGPath; 

後:

[layer addAnimation:a forKey:@"path"];