Ios-core Animation (Core animation)

Source: Internet
Author: User

Core Animation, the Chinese translation is a central animation, it is a very powerful set of animation processing API, using it can make very beautiful animation effect, and often do more with less. In other words, very powerful functionality can be achieved with a small amount of code.
Core animation can be used on Mac OS X and iOS platforms.
The animation execution of Core animation is performed in the background and does not block the main thread.
It is important to note that the Core animation is directly acting CALayer on, not uiview.

The relationship between Calayer and UIView

In iOS, what you can see and touch is basically uiview, such as a button, a text label, a text input box, an icon, and so on, all of which are uiview.

In fact, UIView can be displayed on the screen entirely because of a layer inside it:

When you create a UIView object, a layer (that is, the Calayer object) is automatically created inside UIView, which can be accessed through the Layer property of the UIView.

@property(nonatomic,readonly,retain) CALayer *layer;

When UIView needs to be displayed on the screen, the DrawRect: method is called to draw, and all the content is drawn on its own layer, and after the drawing is finished, the layer is copied to the screen, so the UIView is displayed.

In other words, the UIView itself does not have the ability to display, it is the inner layer of the display function.

Therefore, it is convenient to adjust some appearance properties of UIView by adjusting the Calayer object.

Basic properties of Calayer

Width and Height:

@property CGRect bounds;

Location (default midpoint, determined by Anchorpoint):

@property CGPoint position;

The anchor point (x, y range is 0-1), which determines the meaning of the position:

anchorPoint;

Background color (cgcolorref type):

@property CGColorRef backgroundColor;

Deformation properties:

@property CATransform3D transform;
The role of position and Anchorpoint

@property cgpoint position;:

Used to set the position of the Calayer in the parent layer
The upper left corner of the parent layer is the origin (0, 0).

@property Cgpoint Anchorpoint;:

Called "anchor points", "anchors",
Determines which point on the Calayer is in the position indicated by the position attribute.
The origin (0, 0) in its upper left corner,
Its x, y range is 0~1, the default is the center point (0.5, 0.5)

Examples of the relationship between Anchorpoint and position:

If the anchor point Anchorpoint is the default value, which is the midpoint (0.5,0.5), and the position of the layer is set to (0,0) the upper-left point of the parent layer, the layer sees only one-fourth of the part in the parent layer.


Anchorpoint and position implicit animations

Root and non-root layers:

    • Each uiview is associated with a calayer, and we can call this layer the root layer (root)

    • All non-root layers, which are manually created Calayer objects, have implicit animations

When you modify some properties of a non-root layer, some animations are automatically generated by default, which are called Animatable properties (animated property).

Some of the most common animated properties are:

    • Bounds: Used to set the width and height of the calayer. Modifying this property will result in a scaled animation
    • BackgroundColor: Used to set the background color of the calayer. Modifying this property will result in a gradient animation of the background color
    • Position: The location to set the Calayer. Modifying this property will result in a panning animation

Implicit animations can be turned off through transactions:

[CATransaction begin];// 关闭隐式动画[CATransaction setDisableActions:YES];self.myview.layer.position = CGPointMake(10, 10);[CATransaction commit];
Choice of UIView and Calayer

By Calayer, you can make the same interface effect as Uiimageview.

Since Calayer and UIView all can achieve the same display effect, then who should choose who is good?

In fact, the comparison of Calayer,uiview more than one 事件处理 function. In other words, Calayer cannot handle user touch events, and UIView can
So, if the displayed things need to interact with the user, with UIView, if you do not need to interact with the user, with UIView or calayer can be. Of course, the performance of Calayer will be higher because it has less 事件处理 functionality and more 轻量级 .

Why can't calayer use Uicolor,uiimage directly?
layer.backgroundColor = [UIColor redColor].CGColor;

First, Calayer is defined in the Quartzcore framework, and Cgimageref, cgcolorref two data types are defined in the Coregraphics framework.
, while Uicolor and uiimage are defined in the Uikit framework.

Second, the Quartzcore framework and Coregraphics framework are available across platforms and can be used on both iOS and Mac OS x.
However, Uikit can only be used in iOS.

Therefore, in order to ensure portability, quartzcore can not use UIImage, Uicolor, can only use Cgimageref, Cgcolorref.

If it is not a post-XCODE5 version, it needs to be added QuartzCore.framework and introduced with the corresponding framework first QuartzCore/QuartzCore.h .

Core Animation structure
Inheritance relationship

Where the gray dashed line represents the inheritance relationship, red indicates adherence to the agreement.

All classes in the core animation adhere to the Camediatiming protocol.
Caanaimation is an abstract class that has no animation effect and has to be animated with its subclasses.

Caanimationgroup and Catransition have an animated effect, Caanimationgroup is an animation group that can be scaled at the same time, rotated (with multiple animations at the same time).

Catransition is a transition animation, the interface between the jump (toggle) can be animated with transitions.

Capropertyanimation is also an abstract class, itself does not have animation effect, only sub-class.

Cabasicanimation and Cakeyframeanimation:
Cabasicanimation basic animations, do some simple effects.
Cakeyframeanimation frame animation, do some continuous smooth animation.

Basic use

Take the basic animation as an example:

    • First you need to have a calayer layer.
    • Initializes a Cabasicanimation object that sets the related properties to the object.
    • You can start the animation by adding the basic animation object to the Calayer object.
CALayer *layer = [CALayer layer];...CABasicAnimation *animation = [CABasicAnimation animation];anmation.keyPath = @"transform.scale";anmation.toValue = @0;[layer addAnimation:animation forKey:nil];
caanimation--Introduction

Is the parent of all animated objects and is responsible for controlling the duration and speed of the animation, an abstract class that cannot be used directly, and should use its specific subclasses.

Basic Property Description:

Properties Description
Duration Duration of animation
RepeatCount Number of repetitions, infinite loops can be set huge_valf or maxfloat
RepeatDuration Repeat Time
Removedoncompletion The default is yes, which causes the animation to be removed from the layer after it has finished executing, and the shape reverts to the state before the animation was executed. If you want the layer to remain displayed after the animation has been executed, set it to no, but also set to fillModekCAFillModeForwards
Fillmode Determines the behavior of the current object during a non-active time period. For example, before the animation starts or the animation ends
BeginTime Can be used to set the animation delay execution time, if you want to delay 2s, set to Cacurrentmediatime () +2,cacurrentmediatime () is the current time of the layer
Timingfunction Speed control function to control the rhythm of animation operation
Delegate Animation agent

fillModeSetting of the property:

    • Kcafillmoderemoved This is the default value, that is, when the animation starts and after the end of the animation, the animation has no effect on the layer, the end of the animation, the layer will revert to the previous state

    • Kcafillmodeforwards when the animation is finished, the layer will remain the last state of the animation

    • Kcafillmodebackwards before the animation begins, just add the animation to a layer,layer and immediately enter the initial state of the animation and wait for the animation to begin.

    • Kcafillmodeboth This is actually the synthesis of the above two. The layer is in the initial state of the animation before the animation is added, and the layer retains the last state of the animation after the animation is finished.

Speed control function (camediatimingfunction):

    • Kcamediatimingfunctionlinear (linear): constant speed, gives you a relatively static feeling

    • Kcamediatimingfunctioneasein (Progressive): Animation slowly enters, then accelerates to leave

    • Kcamediatimingfunctioneaseout (Fade Out): Animation enters at full speed, then slows down to the destination

    • Kcamediatimingfunctioneaseineaseout (gradual fade Out): The animation slowly enters, the middle accelerates, then slows down to reach the destination. This is the default animation behavior.

Caanimation defines the proxy method in the classification

 @interface  NSObject (caanimationdelegate) /* Called when the animation Begins its active duration. *///animation starts with a call-(void) Animationdidstart: ( caanimation *) Anim; /* called when the animation either completes it active duration or * is removed from the Obje CT It is attached to (i.e. the layer). ' Flag ' * is true if the animation reached the end of its active duration * without being removed. *///after the end of the animation call-(void) Animationdidstop: ( caanimation *) Anim finished: (bool) Flag; @end              
Pause and resume animations on Calayer
#pragma mark pauses the Calayer animation-(void) Pauselayer: (calayer*) layer{Cftimeinterval pausedtime = [Layer convertTime:Cacurrentmediatime () Fromlayer:NIL];Let the calayer time stop walking layer.speed =0.0;Let Calayer time stay at pausedtime this moment layer.timeoffset = Pausedtime;}#pragma mark recovers Calayer animation-(void) Resumelayer: (calayer*) layer{ cftimeinterval pausedtime = Layer.timeoffset; //1. Let the calayer time continue to walk layer.speed = 1.0; //2. Cancel the last recorded stay time Layer.timeoffset = 0.0; //3. Cancel the last set time Layer.begintime = 0.0; //4. Calculate the time of the pause (you can also use Cacurrentmediatime ()-pausedtime) cftimeinterval timesincepause = [Layer convertTime: cacurrentmediatime () Fromlayer:Nil]-pausedtime; //5. Set the start time relative to the parent coordinate system (go back timesincepause) layer.begintime = timesincepause;}       
Capropertyanimation

is a subclass of Caanimation, also an abstract class, to create an animated object, you should use its two subclasses: Cabasicanimation and Cakeyframeanimation.

Basic Property Description:

Properties Description
KeyPath By specifying a property name of Calayer as KeyPath (nsstring type), and modifying the value of this property of Calayer, the corresponding animation effect is achieved. For example, if you specify @ "position" as KeyPath, the value of the position property of the Calayer is modified to achieve the animated effect of panning
cabasicanimation--Basic Animations

Property Description:

Properties Description
Fromvalue KeyPath the initial value of the corresponding property
Tovalue KeyPath the end value of the corresponding property

Animation Process Description:

As the animation progresses, the value of the keypath corresponding property is gradually changed from Fromvalue to Tovalue for the duration of the duration length.

KeyPath content is an animated animatable property of Calayer.

If fillMode = kCAFillModeForwards at removedOnComletion = NO the same time, after the animation finishes, the layer remains displayed after the animation is executed. But in essence, the property value of the layer is not really changed until the animation is executed 初始值 .

cakeyframeanimation--Key-Frame animations

Keyframe animation is also a subclass of Capropertyanimation, with the CABasicAnimation的区别 following:

    • Cabasicanimation can only change from one numeric value (Fromvalue) to another (Tovalue), and Cakeyframeanimation saves the values with a Nsarray
    • Cabasicanimation can be seen as a cakeyframeanimation with only 2 keyframes

Property Description:

Properties Description
Values The Nsarray object. The elements inside are called "keyframes" (keyframe). The animated object displays each keyframe in the values array in the specified time (duration), in turn
Path You can set a cgpathref, Cgmutablepathref, and let the layer move along the path trajectory. Path only works on Calayer's anchorpoint and position. If path is set, then values will be ignored
Keytimes You can specify a corresponding point in time for the corresponding keyframe, with a value range of 0 to 1.0,keytimes each time value corresponds to each frame in values. If Keytimes is not set, the time of each keyframe is equally divided
caanimationgroup--Animation Group

Animation group, which is a subclass of Caanimation, can save a set of animated objects, and after the Caanimationgroup object is added to the layer, all animated objects in the group can run concurrently simultaneously.

By default, a set of animated objects runs at the same time, or you can change the start time of an animation by setting the properties of the animated object beginTime .

Property Description:

Properties Description
Animations A nsarray used to hold a set of animated objects
catransition--transition Animations

Catransition is a subclass of caanimation that is used to animate transitions and animate layers to move out of the screen and into the screen. iOS has less transition animations than Mac OS X.

The Uinavigationcontroller is an animated effect that pushes the controller's view onto the screen through catransition.

Property Description:

Properties Description
Type Animation transition Type
Subtype Animation over direction
Startprogress Start of animation (percentage in overall animation)
Endprogress Animation end Point (percentage of overall animation)

Transition effect Settings


Type using UIView animation function for transition Animation--Dual view
+ (void)transitionFromView:(UIView *)fromView toView:(UIView *)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void (^)(BOOL finished))completion;
Parameters Description
Duration Animation duration
Option Type of animation
Animations Place the code that changes the properties of the view in this block
Completion This block is automatically called when the animation is finished.
Cadisplaylink

The cadisplaylink is a clock mechanism that is triggered at the screen refresh rate, about 60 times per second.

Cadisplaylink is a timer that keeps the drawing code in sync with the refresh rate of the view, while Nstimer does not ensure the exact time at which the timer is actually triggered.

How to use:

    • Defining Cadisplaylink and developing trigger invocation methods
    • Add a display link to the main run loop queue
// 定义CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(rotationChange)];// 添加到主循环队列[link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    • Start and pause
// 暂停link.paused = YES;// 开始link.paused = NO;

    • The core animation shows us just an illusion that the frame, bounds, and position of the layer will not change after the animation has finished.

    • UIView encapsulated animations will make it true to modify some of the properties of the view.

PS: Apple official website api-caanimation

Ios-core Animation (Core animation)

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.