2013-08-22 39 views
6

我可以創建這樣一個面具:動畫的面具一個UIView

CALayer *mask = [CALayer layer]; 
    mask.contents = (id)[[UIImage imageNamed:@"mask.png"] CGImage]; 
    mask.frame = CGRectMake(0, 0, 10, 10); 
    self.content.layer.mask = mask; 

,這將正確顯示左上角我的內容的10個像素(因爲mask.png只是一個黑色圖像)。不過,我想動畫面具以顯示其餘內容:

[UIView animateWithDuration:3.0 
        animations:^{ 
         mask.frame = self.content.bounds; 
        } 
        completion:^(BOOL finished){ 

        }]; 

問題是沒有動畫。整個內容會立即顯示。爲什麼會發生這種情況,以及如何爲面罩設置動畫,以便從左上方顯示內容?

回答

14

框架是各種其它特性,如位置,邊界,anchorPoint的派生屬性,它已適用於它的任何變換。不建議直接爲此屬性設置動畫,特別是在處理較低級別的CoreAnimation圖層時。

在這種情況下,我會假設你想動畫的範圍。你可以使用上面的UIView動畫方法,但是當直接處理CALayers時,我更喜歡使用動畫的CoreAnimation方法。

CGRect oldBounds = mask.bounds; 
CGRect newBounds = self.content.bounds; 

CABasicAnimation* revealAnimation = [CABasicAnimation animationWithKeyPath:@"bounds"]; 
revealAnimation.fromValue = [NSValue valueWithCGRect:oldBounds]; 
revealAnimation.toValue = [NSValue valueWithCGRect:newBounds]; 
revealAnimation.duration = 3.0; 

// Update the bounds so the layer doesn't snap back when the animation completes. 
mask.bounds = newBounds; 

[mask addAnimation:revealAnimation forKey:@"revealAnimation"]; 
+0

這工作,部分地。我現在可以看到動畫。然而,它停止了一半,而不是揭示整個內容視圖。你知道這可能是爲什麼嗎? – soleil

+0

我不確定是誠實的;仔細檢查內容邊界內的值是否正確。我會充實的答案也會更加強大。 – WDUK

+0

其實這是因爲錨點(由於某些原因,默認爲0.5,0.5)。這解決了它:mask.anchorPoint = CGPointMake(0,0); – soleil