我有一个 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
中偏移该数量。 .
解决方法是定义 path
的CAShapeLayer
位于图层的左上角,例如
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
移动它,以便在您移动它时 center
到center
在它的 superview 中,它将真正居中(现在,如果您将图层的 position
移动到 self.view.center
,它并没有真正居中,因为它将是蓝点图层的左上角在中心); UIView
IBDesignable
的子类将此点作为 View ,以便您可以将其添加到 Storyboard上并查看它的外观;等关于ios - CABasicAnimation 的 toValue 是否相对于初始位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37554068/