使用CADisplayLink'结合'与CAMediaTimingFunction动画UIView.(获得任意曲线)

Dai*_*jan 7 core-animation uiview ios

我正在使用a CADisplayLink来做一个只插入一个值并重绘视图本身的视图动画.

例如,我有一个视图MyView,它有一个属性value,每当设置值时我调用setNeedsDisplay,视图知道要绘制什么.

动画这个我使用CADisplayLink,我希望视图在值之间"变形".我只是通过插入动画的开始和停止值来实现这一点:

- (CGFloat)interpolatedValue:(CGFloat)sourceValue withValue:(CGFloat)targetValue forProgress:(CGFloat)progress;

现在获得一个线性进展很容易并得到一个"特定曲线"(好)但我希望能够利用CAMediaTimingFunction这个(或其他一些预先存在的逻辑 - 我不想重新发明轮子':)

Tom*_*min 3

有一个很棒的要点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
Run Code Online (Sandbox Code Playgroud)

动画视图

#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
Run Code Online (Sandbox Code Playgroud)

如前所述,您甚至可以设置 2 个控制点来创建以三次贝塞尔曲线为模型的计时函数。

self.animationProgress = [RSTimingFunction timingFunctionWithControlPoint1:CGPointMake(0.6, 0.6) controlPoint2:CGPointMake(0.1, 0.8)];
Run Code Online (Sandbox Code Playgroud)

这将产生以下计时动画(使用CAMediaTimingFunction Playground产生)

在此输入图像描述