Animation in iOS

Source: Internet
Author: User

Animation in iOS

This article mainly introduces Core iOS Animation: Core Animation, UIView Animation, Block Animation, UIImageView Frame Animation. Core Animation CoreAnimationUIView Animation Block Animation UIImageView Frame Animation

Directory [-]

Animation in iOS

Core Animation

CAAnimation:

CAPropertyAnimation

CAKeyframeAnimation

CATransition

UIView Animation

Block Animation

Frame Animation of UIImageView

UIActivityIndicatorView

Animation in iOS

Core Animation

Core Animation is a group of very powerful Animation processing APIs that can be used to make brilliant Animation effects and often get twice the result with half the effort. to use it, you need to add QuartzCore. framework and introduce the corresponding framework.

Development steps:

1> Initialize an animation object (CAAnimation) and set animation-related attributes.

2> Add the animation object to the layer (CALayer) and start executing the animation.

In CALayer, many attributes can be animated using CAAnimation, including opacity, position, transform, bounds, and contents (you can search for CALayer Animatable Properties in the API documentation ).

Call the CALayer addAnimation: forKey: add the animation to the layer (CALayer) to trigger the animation. Call removeAnimationForKey to stop the animation in the layer.

The Animation execution process of Core Animation is performed in the background and does not block the main thread.

CAAnimation:

The parent class of all animation objects, which controls the animation duration and speed. It is an abstract class and cannot be used directly. It should be used as a subclass.

Property parsing:

Duration: animation duration.

RepeatCount: Number of animation repetitions.

RepeatDuration: Specifies the animation repetition time.

RemovedOnCompletion: The default value is YES, indicating that the animation will be removed from the layer after execution, and the image will be restored to the state before execution. If you want the layers to remain in the animation state after execution, set it to NO, but set fillMode to kCAFillModeForwards.

FillMode: determines the behavior of the current object in a non-active period. For example, before the animation starts, after the animation ends.

BeginTime: it can be used to set the animation delay execution time. If you want to delay 2 s, set CACurrentMediaTime () + 2 and CACurrentMediaTime () to the current time of the layer.

TimingFunction: A speed control function that controls the animation running pace.

Delegate: animation proxy

CAMediaTimingFunction)

1> kCAMediaTimingFunctionLinear (linear): constant speed, giving you a relatively static feeling

2> kCAMediaTimingFunctionEaseIn

3> kCAMediaTimingFunctionEaseOut: the animation enters at full speed and then slows down to the destination.

4> kCAMediaTimingFunctionEaseInEaseOut: the animation enters slowly, accelerates in the middle, and then slows down to the destination. This is the default animation action.

CAAnimation defines proxy methods in classification

@ InterfaceNSObject

-(Void) animationDidStart :( CAAnimation *) anim;

-(Void) animationDidStop :( CAAnimation *) anim finished :( BOOL) flag;

@ End

FillMode attribute value (it is best to set removedOnCompletion = NO if fillMode is valid)

KCAFillModeRemoved is the default value. That is to say, before and after the animation starts, the animation has no effect on the layer. After the animation ends, the layer will return to the previous state ?.

KCAFillModeForwards after the animation ends, the layer remains in the final state of the animation.

? Before the animation starts, kCAFillModeBackwards adds the animation to a layer, which immediately enters the initial state of the animation and waits for the animation to start. you can set the test code to add an animation to a layer with a latency of 5 seconds. then we will find that when the animation is not started, as long as the animation is added to the layer, the layer is in the initial state of the animation?

KCAFillModeBoth is actually the synthesis of the above two. Before the animation starts, the layer is in the initial state of the animation. After the animation ends, the layer maintains the final state of the animation.

CAPropertyAnimation

The subclass of CAAnimation is also an abstract class. To create an animation object, you should use its two subclasses: CABasicAnimation and CAKeyframeAnimation.

Property parsing:

KeyPath:

You can specify a CALayer attribute named keyPath (NSString type) and modify the value of this attribute to achieve the corresponding animation effect. For example, if you specify @ "position" as keyPath, modify the value of the position attribute of CALayer to achieve the animation effect of translation.

CABasicAnimation

Subclass of CAPropertyAnimation.

Property parsing:

FromValue: the initial value of the corresponding attribute of keyPath.

ToValue: end value of the corresponding attribute of keyPath.

As the Animation continues, the value of the corresponding attribute of keyPath gradually changes from fromValue to toValue within the duration of duration.

If fillMode = kCAFillModeForwards and removedOnComletion = NO, the layers remain in the animation state after the animation is executed. However, in essence, the attribute values of layers are the initial values before the animation is executed and are not actually changed. For example, the initial position value of CALayer is (0, 0), the fromValue of CABasicAnimation is (10, 10), and the toValue is (100,100). Although the layer remains at (100,100) after the animation is executed, the position of the substantive layer is (0, 0)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24 // Pan Animation

CABasicAnimation * anim = [CABasicAnimationanimationWithKeyPath: @ "position"];

// Animation lasts for 1 second

Anim. duration = 1;

// Because CGPoint is a struct, It is packaged into an OC object using NSValue.

Anim. fromValue = [NSValuevalueWithCGPoint: CGPointMake (50, 50)];

Anim. toValue = [NSValuevalueWithCGPoint: CGPointMake (100,100)];

// You can use MyAnim to retrieve the corresponding animation object. For example, you can cancel an animation in the middle.

[LayeraddAnimation: animforKey: @ "MyAnim"];

// Scaling Animation

CABasicAnimation * anim = [CABasicAnimationanimationWithKeyPath: @ "transform"];

// If fromValue is not set, the current status is used as the initial value.

// Change the width to 2 times the original width and the height to 1.5 times the original width.

Anim. toValue = [NSValuevalueWithCATransform3D: CATransform3DMakeScale (2, 1.5, 1)];

Anim. duration = 1;

[LayeraddAnimation: animforKey: nil];

// Rotate the animation

CABasicAnimation * anim = [CABasicAnimationanimationWithKeyPath: @ "transform"];

// Here we use the vector (2 radian, 0) as the axis and rotate π/(90 °)

// If you only rotate on the cell phone plane, set the vector to (0, 0, 1), that is, the Z axis.

Anim. toValue = [NSValuevalueWithCATransform3D: CATransform3DMakeRotation (M_PI_2, 1, 1, 0)];

Anim. duration = 1;

[LayeraddAnimation: animforKey: nil];

CAKeyframeAnimation

The subclass of CApropertyAnimation, which is different from CABasicAnimation:

CABasicAnimation can only be changed from one value (fromValue) to another value (toValue), and CAKeyframeAnimation will use an NSArray to save these values.

Property parsing:

Values: The above NSArray object. The elements are called "key frames" (keyframe ). The animation object will display each key frame in the values array in sequence within the specified time (duration.

Path: you can set a CGPathRef \ CGMutablePathRef to move the layer along with the path. Path only applies to the anchorPoint and position of CALayer. If you set path, values will be ignored.

KeyTimes: You can specify the corresponding time point for the corresponding key frame. The value range is 0 to 1.0. Each time value in keyTimes corresponds to each frame in values. when keyTimes is not set, the time of each key frame is evenly divided.

CABasicAnimation can be viewed as a CAKeyframeAnimation with a maximum of two key frames.

There is also a very important parameter in the Key Frame Animation, that is, the calculationMode, the computing mode. it mainly targets the situation where the content of each frame is a coordinate point, that is, the anchorPoint and position animation. when there are multiple discrete points in a plane coordinate system, they can be discrete, or they can be connected in a straight line for interpolation calculation, you can also use smooth curves to connect them and perform interpolation. calculationMode currently provides the following modes:

The default value of kCAAnimationLinear calculationMode indicates that when the key frame is a coordinate point, the key frames are directly connected to each other for interpolation;

? If kCAAnimationDiscrete is discrete, interpolation is not performed, and all key frames are displayed one by one;

? KCAAnimationPaced makes the animation even, instead of dividing the time by keyTimes or by key frame. In this case, keyTimes and timingFunctions are invalid;

? KCAAnimationCubic performs smooth curve connection and Interpolation Calculation on key frames whose key frames are coordinate points. The main purpose here is to smooth the running trajectory;

KCAAnimationCubicPaced, you can see that it has a certain relationship with kCAAnimationCubic. In fact, the animation runs evenly on the basis of kCAAnimationCubic, that is, the distance between the system and the system time is the same, in this case, keyTimes and timingFunctions are invalid.

CAAnimationGroup

A subclass of CAAnimation that can save a set of animation objects. After adding the CAAnimationGroup object to the layer, all animation objects in the group can run concurrently.

Property parsing:

Animations: NSArray used to save a set of animation objects.

By default, a group of animation objects run simultaneously. You can also set the beginTime attribute of the animation object to change the animation start time.

CATransition

The subclass of CAAnimation, used for transfer animation, can provide animation effects for the layer to remove the screen and move into the screen. IOS has less animation effects than Mac OS X.

UINavigationController is an animation that pushes the Controller view into the screen through CATransition.

Property parsing:

Type: animation transition type

Subtype: animation transition direction

StartProgress: animation start point (percentage in the overall animation)

EndProgress: animation end point (percentage in the overall animation)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27/* transition effect

Fade // cross-fade transition (transition direction not supported) kCATransitionFade

Push // The New View pushes the old view to kCATransitionPush

MoveIn // move the new view to the old view. kCATransitionMoveIn

Reveal // remove the old view and display the new view kCATransitionReveal below

Cube // cube tumble Effect

OglFlip // top, bottom, left, and right flip

SuckEffect // contraction effect, such as a cloth being drawn (transition direction not supported)

RippleEffect // drip effect (transition direction not supported)

PageCurl // page up

PageUnCurl // page flip

CameraIrisHollowOpen // camera lens opening effect (transition direction not supported)

CameraIrisHollowClose // camera lens close effect (transition direction not supported)

*/

/* Transition direction

KCATransitionFromRight

KCATransitionFromLeft

KCATransitionFromBottom

KCATransitionFromTop

*/

// Use of CATransition

CATransition * anim = [CATransitionanimation];

Anim. type = @ "cube"; // animation transition type

Anim. subtype = kCATransitionFromTop; // animation transition direction

Anim. duration = 1; // animation lasts for 1 s

// Proxy. After the animation is executed, the animationDidStop: finished: of delegate is called:

Anim. delegate = self;

UIView Animation

UIKit directly integrates the animation into the UIView class. When some internal attributes change, UIView provides animation support for these changes.

The work required to execute the animation is automatically completed by the UIView class, but you still need to notify the view when you want to execute the animation. Therefore, you need to put the code for changing the attribute in [UIView beginAnimations: nil context: between nil] and [UIView commitAnimations]

Common Methods:

+ (Void) setAnimationDelegate :( id) delegate

Sets the animation proxy object. When the animation starts or ends, a message is sent to the proxy object.

+ (Void) setAnimationWillStartSelector :( SEL) selector

When the animation is about to begin, execute the selector of the delegate object and pass the parameters passed in beginAnimations: context: To the selector.

+ (Void) setAnimationDidStopSelector :( SEL) selector

When the animation ends, run the delegate object selector and pass the parameters passed in beginAnimations: context: To the selector.

?

1

2

3

4

5

6

7

8

9

10 // specifies the animation to be executed

[UIViewbeginAnimations: nilcontext: nil];

// Set the animation duration

[UIViewsetAnimationDuration: 1];

// Set transfer Animation

[UIViewsetAnimationTransition: UIViewAnimationTransitionCurlUpforView: self. viewcache: YES];

// Swap the position of the subview

[Self. viewexchangeSubviewAtIndex: 0 withSubviewAtIndex: 1];

// Submit an animation

[UIViewcommitAnimations];

UIView Animation

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14 + (void) setAnimationDuration :( NSTimeInterval) duration

// Animation duration, in seconds

+ (Void) setAnimationDelay :( NSTimeInterval) delay

// The animation starts after delay seconds.

+ (Void) setAnimationStartDate :( NSDate *) startDate

// Specifies the animation start time. The default value is now.

+ (Void) setAnimationCurve :( UIViewAnimationCurve) curve

// The animation rhythm control. For details, refer to the "Remarks" below"

+ (Void) setAnimationRepeatCount :( float) repeatCount

// Number of animation repetitions

+ (Void) setAnimationRepeatAutoreverses :( BOOL) repeatAutoreverses

// If it is set to YES, the effect of repeated animation execution will be the opposite

+ (Void) setAnimationTransition :( UIViewAnimationTransition) transitionforView :( UIView *) viewcache :( BOOL) cache

// Set the transition effect of the view. The transition specifies the transition type. The cache setting YES indicates that the view cache is used, and the performance is better.

Block Animation

+ (Void) animateWithDuration :( NSTimeInterval) duration delay :( NSTimeInterval) delay options :( UIViewAnimationOptions) options animations :( void (^) (void) animations completion :( void (^) (BOOL finished) completion

Parameter Parsing:

Duration: animation duration

Delay: animation starts after delay seconds.

Options: animation rhythm Control

Animations: place the code to change the view attribute in this block.

Completion: The block is automatically called after the animation ends.

+ (Void) transitionWithView :( UIView *) view duration :( NSTimeInterval) duration options :( UIViewAnimationOptions) options animations :( void (^) (void) animations completion :( void (^) (BOOL finished) completion

Parameter Parsing:

Duration: animation duration

View: view for transition Animation

Options: Transfer animation type

Animations: place the code to change the view attribute in this block.

Completion: The block is automatically called after the animation ends.

+ (Void) transitionFromView :( UIView *) fromView toView :( UIView *) toView duration :( NSTimeInterval) duration options :( UIViewAnimationOptions) options completion :( void (^) (BOOL finished) completion

After the method is called, the following code is executed:

// Add toView to parent View

[FromView. superview addSubview: toView];

// Remove fromView from parent View

[FromView. superview removeFromSuperview];

Parameter Parsing:

Duration: animation duration

Options: Transfer animation type

Animations: place the code to change the view attribute in this block.

Completion: The block is automatically called after the animation ends.

Frame Animation of UIImageView

UIImageView allows a series of images to be displayed in sequence within a specific period of time.

Resolution of related attributes:

AnimationImages: The image to be displayed (an NSArray containing UIImage ).

AnimationDuration: displays the time required for all images in an animation.

AnimationRepeatCount: Number of animation executions (0 by default, indicating an infinite loop)

Analysis of related methods:

-(Void) startAnimating; starts the animation.

-(Void) stopAnimating; stop the animation.

-(BOOL) isAnimating; whether or not the animation is running.

UIActivityIndicatorView

It is a rotation progress wheel, which can be used to inform the user that an operation is in progress. It is generally initialized using initWithActivityIndicatorStyle.

Method Analysis:

-(Void) startAnimating; Start Animation

-(Void) stopAnimating; stop Animation

-(BOOL) isAnimating; whether or not the animation is running

UIActivityIndicatorViewStyle has three values available:

UIActivityIndicatorViewStyleWhiteLarge // large white indicator

UIActivityIndicatorViewStyleWhite // standard white indicator

UIActivityIndicatorViewStyleGray // gray indicator for white background

~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.