gpt4 book ai didi

ios - 为什么 CALayer 和 CAShapeLayer 表现不同

转载 作者:行者123 更新时间:2023-12-01 16:30:27 26 4
gpt4 key购买 nike

首先,我创建了 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:^{ ... block 对动画没有任何影响,为什么?

最佳答案

答案 1:不知道为什么 CAShapeLayerCALayer 是 5 和 10,需要仔细调试,但可能是调整 anchorPoint 或者因为你使用形状层的路径

答案 2:关于对CAShapeLayer的影响:这是因为你给它分配了CGPath,改变了shape layer frame,但没有改变路径。因此,您需要使用正确的坐标设置新的 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 block 中使用它。

此代码应按预期工作:

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

关于ios - 为什么 CALayer 和 CAShapeLayer 表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31908475/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com