要从第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
结合使用将为您提供更平滑的效果.