2013-11-21 47 views
2

目標:
我正在繪製具有漸變的自定義形狀。我也想通過從左到右繪製這種形狀的圖形來製作動畫。動畫CALayer的蒙版蒙版

問題:
下面的代碼工作在iPad模擬器,但它並沒有在我的iPad 4的工作運行iOS 7,有誰知道如何使設備這方面的工作?有沒有不同的方式來達到同樣的效果?使用3個CALayers
我的代碼工作(僅在模擬器):我的代碼的

解釋。

  • gradientLayer保持我的漸變。
  • shapeMaskLayer擁有我自定義的形狀。
  • animationMaskLayer蓬勃生機的道路模擬從左繪製向右

animationMaskLayer --masks--> shapeMaskLayer --masks--> gradientLayer

然後我的動畫的animationMaskLayer幀動畫整個造型。

代碼:

// Animation Mask Rects 
CGPathRef leftStartingRectPath = CGPathCreateWithRect(CGRectMake(0, 0, 0, self.frame.size.height), 0); 
CGPathRef fullViewRectPath = CGPathCreateWithRect(CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), 0); 

// Animation Mask Layer 
CAShapeLayer *animationMaskLayer = [CAShapeLayer layer]; 
animationMaskLayer.path = fullViewRectPath; 
animationMaskLayer.fillColor = UIColor.blackColor.CGColor; 

// Shape Mask Layer 
CAShapeLayer *shapeMaskLayer = [CAShapeLayer layer]; 
shapeMaskLayer.path = CGPathCreateWithEllipseInRect(self.bounds, 0); 
shapeMaskLayer.fillColor = [UIColor blueColor].CGColor; 
shapeMaskLayer.mask = animationMaskLayer; 

// Gradient Layer 
CAGradientLayer *gradientLayer = [CAGradientLayer layer]; 
gradientLayer.frame = self.bounds; 
gradientLayer.colors = self.colors; 
gradientLayer.mask = shapeMaskLayer; 
mountainLayer.anchorPoint = pt(0, 0); 
mountainLayer.position = pt(0, 0); 
[self.layer addSublayer:gradientLayer]; 

// Left To Right Animation 
CABasicAnimation *leftToRightAnimation = [CABasicAnimation animationWithKeyPath:@"path"]; 
leftToRightAnimation.duration = 0.5; 
leftToRightAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; 
leftToRightAnimation.fromValue = (__bridge id)leftStartingRectPath; 
leftToRightAnimation.toValue = (__bridge id)fullViewRectPath; 
leftToRightAnimation.fillMode = kCAFillModeForwards; 
leftToRightAnimation.removedOnCompletion = NO; 
[animationMaskLayer addAnimation:leftToRightAnimation forKey:@"animatePath"]; 

// Memory Management 
CGPathRelease(leftStartingRectPath); 
CGPathRelease(fullViewRectPath); 

回答

4

動畫面具的面具?我很驚訝,即使在模擬器中工作。

你試過嵌套兩層,與父層masksToBounds?然後,您可以在兩個圖層上設置獨立的蒙版,並且外層將使用自己的蒙版有效地矇蔽您的內層(由於masksToBounds)。可能哪個圖層獲取哪個掩碼並不重要(因爲您想要兩個掩碼的交集)。

與你在你的問題中列出的代碼,你只需要添加一行,並註釋掉一條線,以獲得正確的功能:

self.layer.mask = animationMaskLayer; 
// shapeMaskLayer.mask = animationMaskLayer; 
+0

精彩,這個作品!所以在掩碼上設置掩碼並不是CALayers的預期用途?看起來更合適的方法來完成這樣的事情是將圖層作爲子圖層嵌套,然後根據需要在子圖層上設置蒙版。 – bearMountain

+0

@bearMountain:就我所知,CALayer的面具唯一應該關注的是其內容的alpha通道(或者,因爲您使用的是「CAShapeLayer」,所以它的路徑形狀)。就像我之前說過的,我很驚訝模擬器甚至看着面罩的面具。 –