我正在使用CAdisplayLink来执行视图动画,该动画只是插值并重绘视图本身.
例如我有一个视图MyView,它有一个属性值,每当设置值时我调用setNeedsdisplay并且视图知道要绘制的内容.
为了动画这我使用CAdisplayLink,我希望视图在值之间“变形”.我只是通过插入动画的开始和结束值来实现这一点:
– (CGFloat)interpolatedValue:(CGFloat)sourceValue withValue:(CGFloat)targetValue forProgress:(CGFloat)进展;
现在获得一个线性进展很容易并得到一个“特定曲线”(好),但我希望能够利用camediatimingFunction来做到这一点(或者其他一些预先存在的逻辑 – 我不想再次重新发明轮子’: )
解决方法
有这个令人敬畏的要点
RSTiming,在你的情况下可能会很方便.您可以使用标准camediatimingFunction定义定时功能,甚至可以使用2个控制点定义定制功能来定义贝塞尔曲线.
如果我得到你的设置,你可能会有这样的事情:
视图控制器
#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; // defines animation speed
_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; // as an example animate alpha
}
@end
如上所述,您甚至可以设置2个控制点来创建以三次贝塞尔曲线为模型的定时函数.
self.animationProgress = [RSTimingFunction timingFunctionWithControlPoint1:CGPointMake(0.6,0.6) controlPoint2:CGPointMake(0.1,0.8)];
这将产生以下时间动画(使用CAMediaTimingFunction playground制作)