要让动画从点1到2再到3再到2再到1并重复循环,您可以在iOS 7及更高版本中使用animateKeyframesWithDuration
:
someView.frame = frame1;
[UIView animateKeyframesWithDuration:2.0 delay:0.0 options:UIViewKeyframeAnimationOptionAutoreverse | UIViewKeyframeAnimationOptionRepeat animations:^{
[UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:0.5 animations:^{
someView.frame = frame2;
}];
[UIView addKeyframeWithRelativeStartTime:0.5 relativeDuration:0.5 animations:^{
someView.frame = frame3;
}];
} completion:nil];
如果使用自动布局,您可以对约束常量的更改进行动画处理。
[UIView animateKeyframesWithDuration:2.0 delay:0.0 options:UIViewKeyframeAnimationOptionAutoreverse | UIViewKeyframeAnimationOptionRepeat animations:^{
[UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:0.5 animations:^{
topConstraint.constant = 200;
leftConstraint.constant = 200;
[self.view layoutIfNeeded];
}];
[UIView addKeyframeWithRelativeStartTime:0.5 relativeDuration:0.5 animations:^{
topConstraint.constant = 100;
leftConstraint.constant = 300;
[self.view layoutIfNeeded];
}];
} completion:nil];
或者,使用自动布局的方法是先停用约束,然后您可以使用frame
值或其他方式进行动画处理。
在早期版本的iOS中,您可以使用CAKeyframeAnimation
,例如沿着路径进行动画处理:
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(100.0, 100.0)];
[path addLineToPoint:CGPointMake(200.0, 200.0)];
[path addLineToPoint:CGPointMake(100.0, 300.0)];
CAKeyframeAnimation *animatePosition = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animatePosition.path = [path CGPath];
animatePosition.duration = 1.0;
animatePosition.autoreverses = YES;
animatePosition.repeatCount = HUGE_VALF;
[self.someView.layer addAnimation:animatePosition forKey:@"position"];
您可以使用任意数量的点完成此操作。如果您想沿曲线路径(例如圆形或贝塞尔曲线)进行动画,这也是一种有用的技术。
如果只想在两个点之间进行动画,可以使用 animateWithDuration:delay:options:animations:completion:
,例如:
[UIView animateWithDuration:0.5
delay:0.0
options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveEaseInOut
animations:^{
// do whatever animation you want, e.g.,
someView.frame = someFrame1;
}
completion:NULL];
这将使someView
从起始帧移动到someFrame1
并返回。
顺便说一下,结合使用UIViewAnimationOptionCurveEaseInOut
、UIViewAnimationOptionAutoreverse
和UIViewAnimationOptionRepeat
将为您提供更平滑的效果,因为动画会反转和重复。