为什么CALayer和CAShapeLayer表现不同

时间:2015-08-09 20:21:03

标签: ios objective-c uiview calayer cashapelayer

首先,我创建了CAShapeLayer,用于屏蔽底部的UIView,高度为10px,如下所示:

CAShapeLayer *mask = [[CAShapeLayer alloc]init];
CGRect maskRect = CGRectMake(0, self.view.frame.size.height-10, self.view.frame.size.width, 10.0);
CGPathRef path = CGPathCreateWithRect(maskRect, NULL);
mask.path = path;
CGPathRelease(path);
mask.anchorPoint = CGPointMake(0.5, 1.0);
self.view.layer.mask = mask;

在评论上述代码后,我创建了一个CALayer,用于屏蔽底部的UIView,高度为10px,如下所示:

CALayer *mask = [CALayer layer];
mask.contents = (id)[[self getImg]CGImage];
mask.frame = CGRectMake(0, self.view.frame.size.height-5, self.view.frame.size.width, 10.0);
mask.anchorPoint = CGPointMake(0.5, 1.0);
self.view.layer.mask = mask;

问题1:

要完全触摸底部而不是上方或下方的像素,CAShapeLayer我定义的CGRect

CGRectMake(0, self.view.frame.size.height-10, self.view.frame.size.width, 10.0);

CALayer我定义的CGRect

CGRectMake(0, self.view.frame.size.height-5, self.view.frame.size.width, 10.0);

CAShapeLayer为什么为-10,CALayer为什么为-5?

动画代码及其对CAShapeLayerCALayer的影响:

CGRect oldBounds = mask.bounds;
    CGRect newBounds = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height/2);

    [UIView animateWithDuration:1.0 animations:^{
        CABasicAnimation* revealAnimation = [CABasicAnimation animationWithKeyPath:@"bounds"];
        revealAnimation.fromValue = [NSValue valueWithCGRect:oldBounds];
        revealAnimation.toValue = [NSValue valueWithCGRect:newBounds];
        revealAnimation.duration = 0.5;
        [mask addAnimation:revealAnimation forKey:@"revealAnimation"];
    }];
    // Update the bounds so the layer doesn't snap back when the animation completes.
    mask.bounds = newBounds;

CAShapeLayer位置的影响发生了变化但对这样的高度没有影响:

enter image description here

对完美运作的CALayer的影响以及我想要的结果:

enter image description here

问题2: 为什么CAShapeLayer改变了位置而不是高度?

我不知道为什么,但我感觉像CALayer动画不顺利?

问题3:

[UIView animateWithDuration:1.0 animations:^{ ...块对动画没有任何影响,为什么?

1 个答案:

答案 0 :(得分:0)

答案1: 不确定CAShapeLayerCALayer为什么它是5和10,需要仔细调试,但问题可能在于调整anchorPoint或者因为你使用形状图层的path < / p>

答案2: 关于对CAShapeLayer的影响:这是因为您为其分配了CGPath,并更改了形状图层框架,但未更改路径。因此,您需要使用正确的坐标设置新的path属性。像这样:

CGRect maskRect =  CGRect newBounds = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height/2);
CGPathRef path = CGPathCreateWithRect(maskRect, NULL);
mask.path = path;
CGPathRelease(path);

答案3:

CABasicAnimation是一个类,它将执行所有动画,并且您不需要在UIView animateWithDuration块中使用它。

此代码应按预期工作:

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