ios - CABasicAnimation 的 toValue 是否相对于初始位置?

标签 ios objective-c core-animation cabasicanimation

我有一个 CALayer我明确地动画到一个新的位置。我的 toValue属性似乎只相对于图层的初始位置。

    CABasicAnimation *move = [CABasicAnimation animationWithKeyPath:@"position"];
    move.fromValue = [NSValue valueWithCGPoint:CGPointMake(blueDot.position.x, blueDot.position.y)];
    move.toValue = [NSValue valueWithCGPoint:CGPointMake(self.view.center.x, self.view.center.y)];
    move.duration = 1.0;
    [blueDot addAnimation:move forKey:@"myMoveAnimation"];
    blueDot.position = CGPointMake(self.view.center.x, self.view.center.y);

所以这段代码不会将图层重绘到 View 的中心。好像真的把图层重绘到CGPointMake(self.view.center.x + blueDot.position.x, self.view.center.y + blueDot.position.y) ,就像它正在添加 float self.view.center 的值到图层的起始位置。

toValue属性(property)应该是这样的吗?移动我的 blueDot 最干净的方法是什么?到 View 的中心?

编辑:
    -(void)viewDidLoad {
        [super viewDidLoad];

        blueDot = [CAShapeLayer layer];
        [blueDot setPath:[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(self.view.center.x - 60 - 5, 163.5, 10, 10)] CGPath]];
        [blueDot setStrokeColor: [UIColor blueColor]CGColor];
        [blueDot setFillColor:[UIColor blueColor]CGColor];
        [[self.view layer] addSublayer:blueDot];
    }

// 163.5 is a placeholder for another view's position value so it's more readable for you guys.

最佳答案

问题是您正在移动 frame层,但蓝点path这个CAShapeLayer已在该层的 frame 内偏移通过 self.view.center.x - 60 - 5, 163.5 ,您在创建 path 时指定的坐标对于那个CAShapeLayer .因此,当您为 position 设置动画时在图层中,蓝点仍会从这个新的 position 中偏移该数量。 .

解决方法是定义 pathCAShapeLayer位于图层的左上角,例如

CAShapeLayer *blueDot = [CAShapeLayer layer];
blueDot.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(5, 5) radius:5 startAngle:0 endAngle:M_PI * 2 clockwise:true].CGPath;  // note that using arc often generates a better looking circle, probably not noticeable at this size, just probably good practice
blueDot.fillColor = [UIColor blueColor].CGColor;

现在,当您移动 position ,这就是蓝点的原点将移动的地方。

顺便说一句,我通常会创建一个单独的 UIView并添加 CAShapeLayer到那个。这样,您可以享受各种不同的功能:
  • 您可以享受UIView基于 block 的动画;
  • 您可以使用 center移动它,以便在您移动它时 centercenter在它的 superview 中,它将真正居中(现在,如果您将图层的 position 移动到 self.view.center ,它并没有真正居中,因为它将是蓝点图层的左上角在中心);
  • 您可以使用 UIKit Dynamics 将其捕捉到位置或定义其他行为,
  • 如果需要,您可以使用自动布局约束来指定位置,
  • 你可以定义一个 UIView IBDesignable 的子类将此点作为 View ,以便您可以将其添加到 Storyboard上并查看它的外观;等
  • 关于ios - CABasicAnimation 的 toValue 是否相对于初始位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37554068/

    相关文章:

    ios - 无法访问build设置

    iphone - 按下细节披露后的注释细节?

    ios - 打印 C 字符串 (UTF-8) 时的 NSLog() 与 printf()

    iphone - UITextField 在 iOS 5 中导致崩溃,在 iOS 4 中工作正常

    ios - 如何使用 Alamofire 多部分上传多张图片?

    ios - iOS Safari 11.3 上的导航器中没有服务 worker

    objective-c - 如何判断用户何时点击 UITableViewCell?

    ios - CAShapeLayer路径动画——缩小一个圆

    ios - 如何在不单击按钮的情况下开始操作?

    ios - UIView beginAnimations 在自定义属性上太快