The article directories

  • IOS Animation Development

  • design

    • 1. Principle of animation design
      • 1.1 Common IOS animation Classes
      • library
        • 1.1.1 iOS Core Animatio
        • n
        • 1.1.2 iOS CALayer
        • 1.1.2 iOS UIView Animation
          • 1.1.2.1 iOS U
          • IView simple animation use
          • 1.1.2.2 iOS UIView Spring Animation
          • 1.1.2.3 iOS keyThe frame of animation KeyFrames
  • 2. Use of blur effects

  • 3. Use maskView to design animations

  • 4. Use Facebook

  • Gallery POP realizes real attenuation with spring animation

  • 5. Use slow functions to simulate physical animations

  • 6. Use CAEmitterLayer with particle effect

  • 7. Enable CAGradientLayer in iOS

  • with

  • 8. Use of CALayer in iOS

  • 9. IOS drawing API to draw line text geometry

IOS animation development and design

1. Principle of animation design

1.1 common iOS animation class library

1.1.1 iOS Core Animation

Core Animation Core Animation is a set of very powerful Animation processing API, which can be used to make very dazzling Animation effects, and often get twice the result with half the effort.

In other words, very powerful functionality can be achieved with very little code.

Core Animation works on Mac OS X and iOS.

Core Animation executes animations in the background without blocking the main thread.

Note that Core Animation works directly on CALayer, not UIView.

Core Animation video: WWDC Core Animation presentation

Core animation class inheritance structure:



If xcode5 is older than xcode5, you need to add quartzCore. framework and import the corresponding <QuartzCore/ quartzcore.h > framework.

Development steps:

<QuartzCore/ quartzcore.h > < quartzcore.h >

2. Initialize a CAAnimation object and set some animation-related properties

3. Add CAAnimation to CALayer by calling addAnimation:forKey: to start animation

4. Animation in CALayer can be stopped by calling CALayer’s removeAnimationForKey: method

CAAnimation — the parent class of all animation objects

/* CAAnimation -- The parent class of all animation objects is the parent class of all animation objects, which is responsible for controlling the duration and speed of the animation. It is an abstract class, and should not be used directly. RepeatDuration: set HUGE_VALF or MAXFLOAT to repeatDuration: removedOnCompletion: The default value is YES, which means the animation is removed from the layer and the image is restored to its original state. Set it to NO if you want the layer to look like it has been animated, but also set fillMode to kcafillmodeforward *fillMode: determines the behavior of the current object during the non-active period. For example, before the animation begins or after the animation ends CACurrentMediaTime()+2. CACurrentMediaTime() is the current time of the layer. Animation agent */Copy the code

CAAnimation — Animation fill mode

/* CAAnimation -- The value of the fillMode property for the animation fillMode. (To allow fillMode to work, set removedOnCompletion = NO.) So, before the animation starts and after the animation ends, the animation has no effect on the layer. After the animation ends, the layer will be restored to its previous state. Kcafillmodeforward when the animation ends, KCAFillModeBackwards - Once you add a layer to the animation before it can start, the layer will move to its original state and wait for the animation to start. KCAFillModeBoth is actually a combination of these two. After the animation is added, the layer is in the initial state of the animation until it starts, and after the animation is finished, the layer remains in the last state of the animation */Copy the code

CAAnimation – speed control function

/ * CAAnimation - speed control function control function (CAMediaTimingFunction) kCAMediaTimingFunctionLinear (linear) : Uniform, give you the feeling of a relatively static kCAMediaTimingFunctionEaseIn (gradual) : enter slowly, then accelerates leave kCAMediaTimingFunctionEaseOut (gradually) : Full into the animation, then decelerate the destination kCAMediaTimingFunctionEaseInEaseOut (gradual fading out) : enter slow, intermediate speeds up, and then slow down to arrive at the destination. This is the default animation behavior. Animate the execution of the rhythm anim. TimingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionLinear]; * /Copy the code

CAPropertyAnimation

/* CAPropertyAnimation is a subclass of CAAnimation, which is an abstract class. To create an animation object, use two subclasses: CABasicAnimation CAKeyframeAnimation The corresponding animation effect can be achieved by specifying a CALayer attribute named keyPath (NSString type) and modifying the value of this attribute of CALayer. For example, by specifying @ "position" as keyPath, you can modify the position property of CALayer to achieve a panned animation */Copy the code

CABasicAnimation — Basic animation

/* CABasicAnimation -- CABasicAnimation -- CABasicAnimation KeyPath: name of the property to be changed (string) fromValue: initial value of the corresponding property keyPath toValue: end value of the corresponding property As the animation progresses, for a duration of duration, The keyPath property gradually changes from fromValue to toValue keyPath, which is CALayer's Animatable property If fillMode= kcafillmodeforward and removedOnComletion=NO, then after the animation is finished, the layer will keep displaying the animation state. But in essence, the layer properties are the same as they were before the animation was executed and haven't really changed. * /Copy the code

CABasicAnimation creates the animation

CABasicAnimation *anim = [CABasicAnimation animation]; // Setting the animation object keyPath determines what animation to perform, and which layer property to call to perform the animation position: pan keyPath = @"position"; / / packaged into object anim. FromValue = [NSValue valueWithCGPoint: CGPointMake (0, 0)];; anim.toValue = [NSValue valueWithCGPoint:CGPointMake(200, 300)]; Anim. Duration = 2.0; Anim. removedOnCompletion = NO; anim.removedOnCompletion = NO; // Keep up to date anim.fillMode = kcafillmodeforward; // addAnimation [self.layer addAnimation:anim forKey:nil];Copy the code

CABasicAnimation — Basic animation

/* CABasicAnimation -- CABasicAnimation -- CABasicAnimation KeyPath: name of the property to be changed (string) fromValue: initial value of the corresponding property keyPath toValue: end value of the corresponding property As the animation progresses, for a duration of duration, The keyPath property gradually changes from fromValue to toValue keyPath, which is CALayer's Animatable property If fillMode= kcafillmodeforward and removedOnComletion=NO, then after the animation is finished, the layer will keep displaying the animation state. But in essence, the layer properties are the same as they were before the animation was executed and haven't really changed. * /Copy the code

CABasicAnimation creates the animation

CABasicAnimation *anim = [CABasicAnimation animation]; // Setting the animation object keyPath determines what animation to perform, and which layer property to call to perform the animation position: pan keyPath = @"position"; / / packaged into object anim. FromValue = [NSValue valueWithCGPoint: CGPointMake (0, 0)];; anim.toValue = [NSValue valueWithCGPoint:CGPointMake(200, 300)]; Anim. Duration = 2.0; Anim. removedOnCompletion = NO; anim.removedOnCompletion = NO; // Keep up to date anim.fillMode = kcafillmodeforward; // addAnimation [self.layer addAnimation:anim forKey:nil];Copy the code

1.1.2 iOS CALayer

In iOS, everything that you can see and touch is basically a UIView, like a button, a text label, a text input field, an icon, all of those things are UIViews. The only reason UIView stays on screen is because of a layer inside it.

When a UIView object is created, a layer (CALayer object) is automatically created inside the UIView, which is accessible through the Layer property of UIView. When the UIView needs to be displayed on the screen, the drawRect: method is called to draw, and everything is drawn on its own layer. When the drawing is done, the system copies the layer onto the screen, and the UIView is displayed.

In other words, UIView doesn’t display itself, it’s the layers inside it that do. UIView only displays because of the CALayer object inside it. Therefore, by manipulating the CALayer object, you can easily adjust UIView’s interface properties, such as shadows, rounded corners, border width, and color.

CALayer some attributes:

// The width and height of the CALayer @property CGRect bounds; // Position (the default is the midpoint, which is determined by anchorPoint) @property CGPoint position; @property CGPoint anchorPoint; @property CGPoint anchorPoint; @property CGPoint anchorPoint; / / the background color (CGColorRef type) @ propertyCGColorRefbackgroundColor; // @property CATransform3D transform; // borderColor (CGColorRef type) @property CGColorRef borderColor; @property CGFloat borderWidth; // property CGFloat cornerRadius; // Contents (e.g. CGImageRef) @property(retain) id contents;Copy the code

1.1.2 iOS CALayer

In iOS, everything that you can see and touch is basically a UIView, like a button, a text label, a text input field, an icon, all of those things are UIViews.

The only reason UIView stays on screen is because of a layer inside it.

When a UIView object is created, a layer (CALayer object) is automatically created inside the UIView, which is accessible through the Layer property of UIView. When the UIView needs to be displayed on the screen, the drawRect: method is called to draw, and everything is drawn on its own layer. When the drawing is done, the system copies the layer onto the screen, and the UIView is displayed.

In other words, UIView doesn’t display itself, it’s the layers inside it that do.

UIView only displays because of the CALayer object inside it. Therefore, by manipulating the CALayer object, you can easily adjust UIView’s interface properties, such as shadows, rounded corners, border width, and color.

CALayer some attributes:

// The width and height of the CALayer @property CGRect bounds; // Position (the default is the midpoint, which is determined by anchorPoint) @property CGPoint position; @property CGPoint anchorPoint; @property CGPoint anchorPoint; @property CGPoint anchorPoint; / / the background color (CGColorRef type) @ propertyCGColorRefbackgroundColor; // @property CATransform3D transform; // borderColor (CGColorRef type) @property CGColorRef borderColor; @property CGFloat borderWidth; // property CGFloat cornerRadius; // Contents (e.g. CGImageRef) @property(retain) id contents;Copy the code

You can set the background image of UIView by setting contents property. Note that the background image must be CGImage to display. We can add the background image after UIImage object. CGImage is directly converted, and after conversion, it needs to be preceded by (ID) for strong transformation.

Self.view.layer. contents = (__bridge id _Nullable)([UIImage imageNamed:@"123"].cgImage);Copy the code

Note that UIView’s CALayer object (layer) can access this layer through the Layer property. Note that this default layer cannot be recreated, but sub-layers can be added to it. UIView can add subviews through the addSubview: method. Similarly, CALayer can add subviews through the addSublayer: method. A CALayer object has two important properties, position and anchorPoint.

Position and anchorPoint properties are CGPoint positions that can be used to set CALayer’s position in the parent level, starting with the upper-left corner of the parent level (0, 0)

The anchorPoint, called the “anchorPoint,” determines which point on CALayer’s body will be in the position indicated by the position property. Its x and y values range from 0 to 1. The default value is (0.5, 0.5).

AnchorPoint is the center point of the view, and position is the position of the view, which overlaps with the center point. So we can modify the view’s layer.anchorPoint or layer.position to achieve specific animation effects during development.

Example: Create a CALayer and add it to the layer of the controller’s view

CALayer *myLayer = [CALayer layer]; Mylayer. bounds = CGRectMake(0, 0, 100, 100); // Set the width and height of the layer (100x100). Mylayer. position = CGPointMake(100, 100); mylayer. position = CGPointMake(100, 100); // set the backgroundColor of the layer: red mylayer.backgroundcolor = [UIColor redColor].cgcolor; // Add myLayer to controller view layer [self.view.layer addSublayer:myLayer];Copy the code

An implicit animation

Root layer and non-root layer:

Every UIView has a CALayer associated with it by default, and we can call that Layer Root Layer. All non-root layers, manually created CALayer objects, have implicit animations

Some animation effects are automatically generated by default when some Properties of the non-root Layer are modified, and these Properties are called Animatable Properties.

A few common animatable properties:

// Bounds: Used to set the width and height of the CALayer. Modifying this property produces the zoom animation //backgroundColor: used to set the backgroundColor of the CALayer. Changing this property produces a gradient animation of the background color //position: Used to set the position of the CALayer. Changing this property produces pan animations // Implicit animations can be closed by transaction: [CATransaction begin]; // Disable implicit animation [CATransaction setDisableActions:YES]; self.myview.layer.position = CGPointMake(10, 10); [CATransaction commit];Copy the code

 

1.1.2 iOS UIView Animation

1.1.2.1 iOS UIView Simple Animation use

UIView animations are the cheapest and most commonly used animations in iOS development.

UIView animation could set the animation attributes are: frame, bounds, center, the transform, alpha, backgroundColor, contentStretch example:

OC code, simple animation Settings

// Start animation: // first argument: animation identifier // second argument: Additional parameters, under the condition of setting agent, this parameter will be sent to the setAnimationWillStartSelector and setAnimationDidStopSelector specified method, most of the cases, Set to nil. [UIView beginAnimations:(nullable NSString *) context:(nullable void *)]; [UIView commitAnimations]; // Animation parameter properties: // animation duration [UIView setAnimationDuration:(NSTimeInterval)]; [UIView setAnimationDelegate (nullable ID)]; / / set the animation to proxy objects at the beginning of SEL [UIView setAnimationWillStartSelector: (nullable SEL)]; [UIView setAnimationDelay:(NSTimeInterval)]; [UIView setAnimationRepeatCount:(float)]; UIViewAnimationCurve /* UIViewAnimationCurve; UIViewAnimationCurveEaseInOut, / / slow in slow out UIViewAnimationCurveEaseIn (default), / / slow into UIViewAnimationCurveEaseOut, / / at a constant speed slow UIViewAnimationCurveLinear / / * / [UIView setAnimationCurve: (UIViewAnimationCurve)]; /* If the last animation is playing and has not finished, we will make a new animation: when YES: the animation will start from the state of the last animation when NO: Animation will be from the previous animation as specified by the final state played (on a animation end immediately at this time) * / [UIView setAnimationBeginsFromCurrentState: YES]; / / sets whether the animation to continue instead of animation [UIView setAnimationRepeatAutoreverses: (BOOL)]; [UIView setAnimationsEnabled:(BOOL)]; [UIView setAnimationsEnabled:(BOOL)]; // Set the transition effect of the view. UIViewAnimationTransition enumeration values below UIViewAnimationTransitionNone, / / no use animation UIViewAnimationTransitionFlipFromLeft, / / turn pages from left to right UIViewAnimationTransitionFlipFromRight, / / spin flip UIViewAnimationTransitionCurlUp from right to left, / / from down to up curling flip UIViewAnimationTransitionCurlDown, / / curling down on page Need the second argument: transition effects the View of the third argument: whether to use View caching, YES: the View at the end of the beginning and render once; NO: view in every frame render * / [UIView setAnimationTransition: UIViewAnimationTransition forView: nonnull UIView *) cache: (BOOL)];Copy the code

The block sets the basic UIView animation:

[UIView animateWithDuration:(NSTimeInterval) // Animations :^{// Animations performed}]; Animations :^{// Animations performed} completion:^(BOOL Finished) {// Animation performed after submission}]; [UIView animateWithDuration:(NSTimeInterval) // animation duration delay:(NSTimeInterval) // animation delay time Animations :^{// Animations performed} completion:^(BOOL finished) {// Animations performed after submission}];Copy the code
1.1.2.2 iOS UIView Spring Animation

IOS 7.0 after the addition of Spring Animation (IOS system Animation most of the use of Spring Animation, applicable to all can be added to the Animation properties) example:

[UIView animateWithDuration:(NSTimeInterval)// animation duration delay:(NSTimeInterval)// animation delay UsingSpringWithDamping :(CGFloat)// vibration effect, the range is 0~1, the smaller the value, the more obvious the vibration effect. Options :(UIViewAnimationOptions)// Animations :^{// Animations performed} completion:^(BOOL finished) {// Animations performed after submission }];Copy the code
1.1.2.3 iOS KeyFrames animation

For example,

//IOS7.0 added keyframe animation, support for attribute keyframes, Do not support the path to the key frames [UIView animateKeyframesWithDuration: (NSTimeInterval) / / animation duration delay: (NSTimeInterval) / / animation delay the time Options: (UIViewKeyframeAnimationOptions) / / animation effect of transition animations: ^ {/ / perform keyframe animation} completion: ^ (BOOL finished) {/ / animation commit after operation }]; / / common property enumeration values: / / UIViewKeyframeAnimationOptions enumeration values is as follows, can use a combination of: UIViewAnimationOptionLayoutSubviews / / animation when layout child controls UIViewAnimationOptionAllowUserInteraction / / animation allows user interaction UIViewAnimationOptionBeginFromCurrentState UIViewAnimationOptionRepeat / / / / starting from the current state animation infinite repeated animations UIViewAnimationOptionAutoreverse / / perform animation loop UIViewAnimationOptionOverrideInheritedDuration / / ignore nested animation the execution time of the setting UIViewAnimationOptionOverrideInheritedOptions set UIViewKeyframeAnimationOptionCalculationModeLinear / / / / no father animation operation modes: continuous Discrete UIViewKeyframeAnimationOptionCalculationModePaced UIViewKeyframeAnimationOptionCalculationModeDiscrete / / operation mode: / / operation mode : uniform execution UIViewKeyframeAnimationOptionCalculationModeCubic / / operation mode: smooth UIViewKeyframeAnimationOptionCalculationModeCubicPaced / / operation modes: smoothlyCopy the code

1. Add key frame method:

[UIView addKeyframeWithRelativeStartTime: (double) / / the starting time of the animation (ratio) of the total time relativeDuration: (double) / / animation duration (the proportion of the total time) Animations :^{// Performing animations}];Copy the code

2. Transition animation:

[UIView transitionFromView:(nonnull UIView *) toView:(nonnull UIView *) duration:(NSTimeInterval) Options :(UIViewAnimationOptions) completion:^(BOOL finished) {// Animation completes the submission}]; // During the animation process, fromView is removed from the parent view and toView is added to the parent view. Note that the transition animation is applied to the parent view. This method is equivalent to executing the following two lines of code: [fromView. Superview addSubview:toView]; [fromView removeFromSuperview] [UIView transitionWithView:(nonnull UIView *) duration:(NSTimeInterval) options:(UIViewAnimationOptions) animations:^{ } completion:^(BOOL finished) {// Animation completed after submission}]; [UIView animateWithDuration:3.0 animations:^{self.redview.center = point; self.redview.transform = CGAffineTransformMakeScale (1.5, 1.5); the self. RedView. Transform = CGAffineTransformMakeRotation (M_PI);} completion: ^ (BOOL finished) {[UIView AnimateWithDuration :2.0 animations:^{self.redview. frame = CGRectMake(100, 100, 100, 100); self. RedView. Transform = CGAffineTransformMakeScale (1/1.5, 1/1.5), and the self. RedView. Transform = CGAffineTransformMakeRotation(M_PI); }]; }]; //usingSpringWithDamping; damping effect, range 0~1, The smaller the value, the more obvious the vibration effect. The greater the value the faster the initial / / the options of the animation transition effects [UIView animateWithDuration: 3.0 delay: usingSpringWithDamping 1.0:0.3 InitialSpringVelocity: 1 options: UIViewAnimationOptionAllowUserInteraction animations: ^ {self. RedView. Alpha = 1.0; self.redView.frame = CGRectMake(200, 350, 140, 140); } completion:^(BOOL finished) { [self.redView removeFromSuperview]; }];Copy the code

2. Use of blur effects

3. Use maskView to design animations

4. Use Facebook open source animation library POP for real decay and spring animation

5. Use slow functions to simulate physical animations

6. Use CAEmitterLayer with particle effect

7. Use of CAGradientLayer in iOS

8. Use of CALayer in iOS

9. IOS drawing API to draw line text geometry

The article will continue to be updated, you can also send me a message to get the latest information and interview information. If you have any comments and suggestions, please leave a message to me.

Like IOS partners attention! If you like, give a thumbs-up! Thank you very much! Thank you very much! Thank you very much!

Click to get:IOS Interview Materials

The original link: blog.csdn.net/kyl28288954…