核心动画进度回调

时间:2013-09-16 12:23:30

标签: ios core-animation

当Core Animation在运行时到达某些点时(例如,完成时的50%和66%?),是否有一种简单的方法可以回叫?

我目前正在考虑设置NSTimer,但这并不像我想的那么准确。

4 个答案:

答案 0 :(得分:33)

我终于为这个问题开发了一个解决方案。

基本上我希望每一帧都被召回,并做我需要做的事情。

没有明显的方法来观察动画的进展,但实际上它是可能的:

  • 首先,我们需要创建一个新的CALayer子类,它具有一个名为“progress”的可动画属性。

  • 我们将图层添加到树中,然后创建一个动画,在动画持续时间内将进度值从0驱动到1.

  • 由于我们的progress属性可以设置动画,因此我们的子类会为动画的每一帧调用drawInContext。此函数不需要重绘任何内容,但可以用它来调用委托函数:)

这是类接口:

@protocol TAProgressLayerProtocol <NSObject>

- (void)progressUpdatedTo:(CGFloat)progress;

@end

@interface TAProgressLayer : CALayer

@property CGFloat progress;
@property (weak) id<TAProgressLayerProtocol> delegate;

@end

实施:

@implementation TAProgressLayer

// We must copy across our custom properties since Core Animation makes a copy
// of the layer that it's animating.

- (id)initWithLayer:(id)layer
{
    self = [super initWithLayer:layer];
    if (self) {
        TAProgressLayer *otherLayer = (TAProgressLayer *)layer;
        self.progress = otherLayer.progress;
        self.delegate = otherLayer.delegate;
    }
    return self;
}

// Override needsDisplayForKey so that we can define progress as being animatable.

+ (BOOL)needsDisplayForKey:(NSString*)key {
    if ([key isEqualToString:@"progress"]) {
        return YES;
    } else {
        return [super needsDisplayForKey:key];
    }
}

// Call our callback

- (void)drawInContext:(CGContextRef)ctx
{
    if (self.delegate)
    {
        [self.delegate progressUpdatedTo:self.progress];
    }
}

@end

然后我们可以将图层添加到主图层:

TAProgressLayer *progressLayer = [TAProgressLayer layer];
progressLayer.frame = CGRectMake(0, -1, 1, 1);
progressLayer.delegate = self;
[_sceneView.layer addSublayer:progressLayer];

并将其与其他动画一起制作动画:

CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"progress"];
anim.duration = 4.0;
anim.beginTime = 0;
anim.fromValue = @0;
anim.toValue = @1;
anim.fillMode = kCAFillModeForwards;
anim.removedOnCompletion = NO;

[progressLayer addAnimation:anim forKey:@"progress"];

最后,随着动画的进展,代表将被回调:

- (void)progressUpdatedTo:(CGFloat)progress
{
    // Do whatever you need to do...
}

答案 1 :(得分:12)

如果您不想破解CALayer向您报告进度,还有另一种方法。从概念上讲,您可以使用CADisplayLink来保证每个帧的回调,然后简单地测量自动画开始以来经过的时间除以确定完成百分比的持续时间。

开源库INTUAnimationEngine将此功能非常干净地打包到一个API中,该API看起来几乎与基于UIView块的动画一样:

// INTUAnimationEngine.h

// ...

+ (NSInteger)animateWithDuration:(NSTimeInterval)duration
                           delay:(NSTimeInterval)delay
                      animations:(void (^)(CGFloat percentage))animations
                      completion:(void (^)(BOOL finished))completion;

// ...

您需要做的就是在启动其他动画的同时调用此方法,为durationdelay传递相同的值,然后对于动画的每个帧,将使用当前完成百分比执行animations块。如果你想让你的时间完全同步,那么你可以完全从INTUAnimationEngine驱动你的动画。

答案 2 :(得分:6)

我在接受的答案中使用了tarme建议的CALayer子类的Swift(2.0)实现:

protocol TAProgressLayerProtocol {

    func progressUpdated(progress: CGFloat)

}

class TAProgressLayer : CALayer {

    // MARK: - Progress-related properties

    var progress: CGFloat = 0.0
    var progressDelegate: TAProgressLayerProtocol? = nil

    // MARK: - Initialization & Encoding

    // We must copy across our custom properties since Core Animation makes a copy
    // of the layer that it's animating.

    override init(layer: AnyObject) {
        super.init(layer: layer)
        if let other = layer as? TAProgressLayerProtocol {
            self.progress = other.progress
            self.progressDelegate = other.progressDelegate
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        progressDelegate = aDecoder.decodeObjectForKey("progressDelegate") as? CALayerProgressProtocol
        progress = CGFloat(aDecoder.decodeFloatForKey("progress"))
    }

    override func encodeWithCoder(aCoder: NSCoder) {
        super.encodeWithCoder(aCoder)
        aCoder.encodeFloat(Float(progress), forKey: "progress")
        aCoder.encodeObject(progressDelegate as! AnyObject?, forKey: "progressDelegate")
    }

    init(progressDelegate: TAProgressLayerProtocol?) {
        super.init()
        self.progressDelegate = progressDelegate
    }

    // MARK: - Progress Reporting

    // Override needsDisplayForKey so that we can define progress as being animatable.
    class override func needsDisplayForKey(key: String) -> Bool {
        if (key == "progress") {
            return true
        } else {
            return super.needsDisplayForKey(key)
        }
    }

    // Call our callback

    override func drawInContext(ctx: CGContext) {
        if let del = self.progressDelegate {
            del.progressUpdated(progress)
        }
    }

}

答案 3 :(得分:1)

移植到Swift 4.2:

protocol CAProgressLayerDelegate: CALayerDelegate {
    func progressDidChange(to progress: CGFloat)
}

extension CAProgressLayerDelegate {
    func progressDidChange(to progress: CGFloat) {}
}

class CAProgressLayer: CALayer {
    private struct Const {
        static let animationKey: String = "progress"
    }

    @NSManaged private(set) var progress: CGFloat
    private var previousProgress: CGFloat?
    private var progressDelegate: CAProgressLayerDelegate? { return self.delegate as? CAProgressLayerDelegate }

    override init() {
        super.init()
    }

    init(frame: CGRect) {
        super.init()
        self.frame = frame
    }

    override init(layer: Any) {
        super.init(layer: layer)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.progress = CGFloat(aDecoder.decodeFloat(forKey: Const.animationKey))
    }

    override func encode(with aCoder: NSCoder) {
        super.encode(with: aCoder)
        aCoder.encode(Float(self.progress), forKey: Const.animationKey)
    }

    override class func needsDisplay(forKey key: String) -> Bool {
        if key == Const.animationKey { return true }
        return super.needsDisplay(forKey: key)
    }

    override func display() {
        super.display()
        guard let layer: CAProgressLayer = self.presentation() else { return }
        self.progress = layer.progress
        if self.progress != self.previousProgress {
            self.progressDelegate?.progressDidChange(to: self.progress)
        }
        self.previousProgress = self.progress
    }
}

用法:

class ProgressView: UIView {
    override class var layerClass: AnyClass {
        return CAProgressLayer.self
    }
}

class ExampleViewController: UIViewController, CAProgressLayerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()

        let progressView = ProgressView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        progressView.layer.delegate = self
        view.addSubview(progressView)

        var animations = [CAAnimation]()

        let opacityAnimation = CABasicAnimation(keyPath: "opacity")
        opacityAnimation.fromValue = 0
        opacityAnimation.toValue = 1
        opacityAnimation.duration = 1
        animations.append(opacityAnimation)

        let progressAnimation = CABasicAnimation(keyPath: "progress")
        progressAnimation.fromValue = 0
        progressAnimation.toValue = 1
        progressAnimation.duration = 1
        animations.append(progressAnimation)

        let group = CAAnimationGroup()
        group.duration = 1
        group.beginTime = CACurrentMediaTime()
        group.animations = animations

        progressView.layer.add(group, forKey: nil)
    }

    func progressDidChange(to progress: CGFloat) {
        print(progress)
    }
}