2013-11-21 155 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”,所以它的路径形状)。就像我之前说过的,我很惊讶模拟器甚至看着面罩的面具。 –