How UIView animations with blocks work under the hood

前端 未结 3 645
伪装坚强ぢ
伪装坚强ぢ 2020-12-31 02:18

I\'m new to Objective-C/iOS programming and I\'m trying to understand how UIView animation works under the hood.

Say I have a code like this:

[UIView         


        
相关标签:
3条回答
  • 2020-12-31 02:51

    Of course I don't know what exactly happens under the hood because UIKit isn't open-source and I don't work at Apple, but here are some ideas:

    Before the block-based UIView animation methods were introduced, animating views looked like this, and those methods are actually still available:

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:duration];
    myView.center = CGPointMake(300, 300);
    [UIView commitAnimations];
    

    Knowing this, we could implement our own block-based animation method like this:

    + (void)my_animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:duration];
        animations();
        [UIView commitAnimations];
    }
    

    ...which would do exactly the same as the existing animateWithDuration:animations: method.

    Taking the block out of the equation, it becomes clear that there has to be some sort of global animation state that UIView then uses to animate changes to its (animatable) properties when they're done within an animation block. This has to be some sort of stack, because you can have nested animation blocks.

    The actual animation is performed by Core Animation, which works at the layer level – each UIView has a backing CALayer instance that is responsible for animations and compositing, while the view mostly just handles touch events and coordinate system conversions.

    I won't go into detail here on how Core Animation works, you might want to read the Core Animation Programming Guide for that. Essentially, it's a system to animate changes in a layer tree, without explicitly calculating every keyframe (and it's actually fairly difficult to get intermediate values out of Core Animation, you usually just specify from and to values, durations, etc. and let the system take care of the details).

    Because UIView is based on a CALayer, many of its properties are actually implemented in the underlying layer. For example, when you set or get view.center, that is the same as view.layer.location and changing either of these will also change the other.

    Layers can be explicitly animated with CAAnimation (which is an abstract class that has a number of concrete implementations, like CABasicAnimation for simple things and CAKeyframeAnimation for more complex stuff).

    So what might a UIView property setter do to accomplish "magically" animating changes within an animation block? Let's see if we can re-implement one of them, for simplicity's sake, let's use setCenter:.

    First, here's a modified version of the my_animateWithDuration:animations: method from above that uses the global CATransaction, so that we can find out in our setCenter: method how long the animation is supposed to take:

    - (void)my_animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations
    {
        [CATransaction begin];
        [CATransaction setAnimationDuration:duration];
    
        animations();
    
        [CATransaction commit];
    }
    

    Note that we don't use beginAnimations:... and commitAnimations anymore, so without doing anything else, nothing will be animated.

    Now, let's override setCenter: in a UIView subclass:

    @interface MyView : UIView
    @end
    
    @implementation MyView
    - (void)setCenter:(CGPoint)position
    {
        if ([CATransaction animationDuration] > 0) {
            CALayer *layer = self.layer;
            CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
            animation.fromValue = [layer valueForKey:@"position"];
            animation.toValue = [NSValue valueWithCGPoint:position];
            layer.position = position;
            [layer addAnimation:animation forKey:@"position"];
        }
    }
    @end
    

    Here, we set up an explicit animation using Core Animation that animates the underlying layer's location property. The animation's duration will automatically be taken from the CATransaction. Let's try it out:

    MyView *myView = [[MyView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    myView.backgroundColor = [UIColor redColor];
    [self.view addSubview:myView];
    
    [self my_animateWithDuration:4.0 animations:^{
        NSLog(@"center before: %@", NSStringFromCGPoint(myView.center));
        myView.center = CGPointMake(300, 300);
        NSLog(@"center after : %@", NSStringFromCGPoint(myView.center));
    }];
    

    I'm not saying that this is exactly how the UIView animation system works, it's just to show how it could work in principle.

    0 讨论(0)
  • 2020-12-31 02:59

    The values intermediate frames for are not specified; the animation of the values (alpha in this case, but also colours, position, etc) is generated automatically between the previously set value and the destination value set inside the animation block. You can affect the curve by specifying the options using animateWithDuration:delay:options:animations:completion: (the default is UIViewAnimationOptionCurveEaseInOut, i.e., the speed of the value change will accelerate and decelerate).

    Note that any previously set animated changes of values will finish first, i.e., each animation block specifies a new animation from the previous end value to the new. You can specify UIViewAnimationOptionBeginFromCurrentState to start the new animation from the state of the already in-progress animation.

    0 讨论(0)
  • 2020-12-31 03:14

    This will change the property specified inside the block from the current value to whatever value you provide, and will do it linearly over the duration.

    So if the original alpha value was 0, this would fade in the label over 2 seconds. If the original values was already 1.0, you wouldn't see any effect at all.

    Under the hood, UIView takes care of figuring out over how many animation frames the change needs to take place.

    You can also change the rate at which the change takes place by specifying an easing curve as a UIViewAnimationOption. Again, UIView handles the tweening for you.

    0 讨论(0)
提交回复
热议问题