有一个很棒的代码片段RSTiming
,它可能对你有用。你可以使用标准的CAMediaTimingFunction定义时间函数,甚至可以使用2个控制点来定义贝塞尔曲线来定义自定义时间函数。
如果我理解你的设置正确,你可能会有类似这样的代码:
ViewController
#import "ViewController.h"
#import "AnimatedView.h"
#include <stdlib.h>
@interface ViewController ()
@property (nonatomic, strong) CADisplayLink *displayLink;
@property (weak, nonatomic) IBOutlet AnimatedView *viewToAnimate;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateFrame)];
[self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
- (void)updateFrame {
[self.viewToAnimate updateAnimation];
}
- (IBAction)updateAnimationTapped:(id)sender {
self.viewToAnimate.value = arc4random_uniform(101) / 100.0;
NSLog(@"Next animation value: %f", self.viewToAnimate.value);
}
@end
AnimatedView
#import "AnimatedView.h"
#import "RSTimingFunction.h"
@interface AnimatedView()
{
CGFloat _lastValue;
CGFloat _progressStep;
CGFloat _currentProgress;
}
@property (nonatomic, strong) RSTimingFunction *animationProgress;
@end
@implementation AnimatedView
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if ((self = [super initWithCoder:aDecoder]))
{
_progressStep = 0.01;
_currentProgress = 1.0;
self.animationProgress = [RSTimingFunction timingFunctionWithName:kRSTimingFunctionEaseInEaseOut];
}
return self;
}
- (void)setValue:(CGFloat)value {
if (_value != value)
{
_lastValue = _value;
_value = value;
_currentProgress = 0.0;
}
}
- (void)updateAnimation
{
if (_currentProgress > 1.0)
return;
_currentProgress += _progressStep;
CGFloat currentAnimationValue = _lastValue + (_value - _lastValue) * [self.animationProgress valueForX:_currentProgress];
self.alpha = currentAnimationValue;
}
@end
正如所说,您甚至可以设置2个控制点来创建基于三次贝塞尔曲线建模的时间函数。
self.animationProgress = [RSTimingFunction timingFunctionWithControlPoint1:CGPointMake(0.6, 0.6) controlPoint2:CGPointMake(0.1, 0.8)];
这将产生以下时间动画(使用CAMediaTimingFunction播放器生成)
![enter image description here](https://istack.dev59.com/jgNwJ.webp)