IOS let your App move

Preface

This paper describes the Core in iOS Animation (Core Animation: implicit animation, display animation), Bessel curve, UIView animation package.

Core Animation, Chinese translation as the core animation, it is a very powerful animation API, use it to make a very dazzling animation, and often more. In other words, the use of a small amount of code can achieve very powerful features. Core Animation can be used in Mac X OS and iOS platform. Core Animation animation execution process is operating in the background, will not block the main thread. It should be noted that Core Animation is a direct effect on the CALayer, not UIView.

The relationship between CALayer and UIView:

In iOS, you can see things are basically UIView, such as a button, a text label, a text input box, an icon, and so on, these are UIView. In fact, UIView can be displayed on the screen, simply because a layer inside it: when a UIView object is created, UIView will automatically create a new layer (the CALayer object), through the layer property UIView can access this layer.

CALayer and UIView is a very similar concept, also has layer, sublayer, backgroundColor, frame… Also have similar properties, we can use UIView as a special kind of CALayer, but UIView can respond to events. In general, layer can be used for two purposes, the two do not conflict with each other: first, the relevant attributes of the view settings, including rounded corners, shadows, borders and other parameters, the two is to achieve the animation control view. Therefore, a view core animation animation, view animation is essentially the.Layer manipulation.

Animation is divided into implicit animation and display animation, we first look at

Implicit animation:

Core Animation is based on a hypothesis that anything on the screen can (or may) do animation. The animation does not require you to manually open in Core Animation, instead you need to explicitly close it or else he will always be there.

When you change one of the CALayer’s animated properties, it doesn’t immediately appear on the screen. Instead, it is a smooth transition from the previous value to a new value. This is the default behavior, you do not need to do additional operations.

It looks like this is great, does not seem to be true, we use a demo to explain: first and the first chapter “layer tree” to create a blue box, and then add a random button to change its color. Click on the button, and you will find that the color of the layer is smooth to a new value instead of a jump.

Random change color:

@interface ViewController ()

@property (nonatomic, weak) IBOutlet UIView*layerView;

@property (nonatomic, weak) IBOutlet CALayer*colorLayer;

@end

@implementation ViewController

– (void) viewDidLoad

{

[super viewDidLoad];

//create sublayer

Self.colorLayer =[CALayer layer];

Self.colorLayer.frame= CGRectMake (50.0f, 50.0f, 100.0f, 100.0f);

Self.colorLayer.backgroundColor=[UIColor blueColor].CGColor;

//add it to our view

[self.layerView.layer addSublayer:self.colorLayer];

}

– (IBAction) changeColor

{//randomize the layer background color

CGFloat red = arc4random (/) / (CGFloat) INT_MAX;

CGFloat green= arc4random () / (CGFloat) INT_MAX;

CGFloat blue= arc4random () / (CGFloat) INT_MAX;

Self.colorLayer.backgroundColor= [UIColor colorWithRed:red green:green blue:blue alpha:1.0].CGColor;

}

@end

IOS let your App move
run effect diagram

In fact, this is the so-called implicit animation. The reason for this is because we do not specify any type of animation. We just changed an attribute, and then Core Animation to decide how and when to animate. Core Animaiton also supports explicit animation, as described below.

But when you change a property, how does Core Animation determine the type and duration of the animation? In fact, the execution time of the animation depends on the settings of the current transaction.

The transaction is actually Core Animation used to include the mechanism of a series of animated property sets, any transaction with the specified can do to change the layer properties of animation have not immediately change, but when the transaction once submitted time to start an animated transition to the new value.

The transaction is managed by the CATransaction class, which is a bit strange, not like you want to manage a simple transaction from its intended name, but rather manages a stack of transactions that you cannot access. CATransaction does not have a property or instance method, and it cannot be created using the +alloc and -init methods. But +begin and +commit can be used to stack or stack.

You can do any animation layer properties are added to the top of the stack, you can use the +setAnimationDuration: method to set the current transaction time of the animation, or through the +animationDuration method to obtain the value (default 0.25 seconds).

Core Animation automatically starts a new transaction in each cycle (run loop loop run iOS is responsible for collecting user input, processing timer or network events and re screen things), even if you do not start a transaction using [CATransaction display begin] type, any property in a run loop cycle change will be together, then do a 0.25 seconds of animation.

Knowing this, we can easily change the color animation time. Of course, we can use the current +setAnimationDuration: method to modify the animation time, but here we start a new transaction, so the modification time will not have other side effects. Because the time to modify the current transaction may cause other animations at the same time (such as screen rotation), it is best to press a new transaction before adjusting the animation.

Run the program, you will find the color of the color is slower than before.

Using CATransaction to control animation time:

– (IBAction) changeColor

{//begin a new transaction

[CATransaction begin];

//set the duration to 1 second animation

[CATransaction setAnimationDuration:1.0];

//randomize the layer background color

CGFloat red = arc4random (/) / (CGFloat) INT_MAX;

CGFloat green= arc4random () / (CGFloat) INT_MAX;

CGFloat blue= arc4random () / (CGFloat) INT_MAX;

Self.colorLayer.backgroundColor= [UIColor green:green blue:blue colorWithRed:red alpha:1.0].CGColor;

//commit the transaction

[CATransaction commit];

}

If you have used UIView animation method to do some animation, it should be no stranger to this model. UIView has two methods, +beginAnimations:context: and +commitAnimations, and the CATransaction +begin and +commit methods are similar. In fact, +beginAnimations:context: and +commitAnimations between all the views or changes in the properties of the layers of the animation is done because of the reasons for setting the CATransaction.

In iOS4, apple adds a block based animation to UIView: +animateWithDuration:animations. It would be easier to write a bunch of attribute animations, but essentially they are doing the same thing.

The CATransaction and +commit methods of +begin are automatically invoked in the +animateWithDuration:animations:, so that all changes in the block attribute will be included in the. This can also avoid developers due to +begin and +commit matching errors caused by the risk.

Completion block

UIView based block animation allows you to provide a complete action at the end of the animation. The CATranscation interface provides the same functionality as the +setCompletionBlock: method. Let’s adjust the previous example to perform some operations after the end of the color change. Let’s add a finished block to switch to another 90 after each color change.

Add a callback after the color animation is completed:

– (IBAction) changeColor

{//begin a new transaction

[CATransaction begin];

//set the duration to 1 second animation

[CATransaction setAnimationDuration:1.0];

//add the animation on spin completion

[CATransaction setCompletionBlock:^{

//rotate the layer 90 degrees

CGAffineTransform transform =self.colorLayer.affineTransform;

Transform=CGAffineTransformRotate (transform, M_PI_4);

Self.colorLayer.affineTransform=transform;

}];

//randomize the layer background color

CGFloat red = arc4random (/) / (CGFloat) INT_MAX;

CGFloat green= arc4random () / (CGFloat) INT_MAX;

CGFloat blue= arc4random () / (CGFloat) INT_MAX;

Self.colorLayer.backgroundColor= [UIColor green:green blue:blue colorWithRed:red alpha:1.0].CGColor;

//commit the transaction

[CATransaction commit];

IOS let your App move
effect diagram

Pay attention to the rotation animation than the color gradient is much faster, this is because the complete block is in the color gradient of the stack until after the transaction commits and executed, so do transform with the default transaction, the default time is 0.25 seconds.

Layer behavior

Now do an experiment and try to animate the UIView associated layer directly instead of a separate layer. Listing 7.4 is a little modification to listing 7.2 code, removing the colorLayer and setting the background color of the layerView associated layer directly.

Listing 7.4 sets the properties of the layer directly

@interfaceViewController ()

@property (nonatomic, weak) IBOutlet UIView*layerView;

@end

@implementation ViewController

– (void) viewDidLoad

{

[super viewDidLoad];

//set the of our backing layer layerView color directly

Self.layerView.layer.backgroundColor =[UIColor blueColor].CGColor;

}

– (IBAction) changeColor

{//begin a new transaction

[CATransaction begin];

//set the duration to 1 second animation

[CATransaction setAnimationDuration:1.0];

//randomize the layer background color

CGFloat red = arc4random (/) / (CGFloat) INT_MAX;

CGFloat green= arc4random () / (CGFloat) INT_MAX;

CGFloat blue= arc4random () / (CGFloat) INT_MAX;

Self.layerView.layer.backgroundColor= [UIColor green:green blue:blue colorWithRed:red alpha:1.0].CGColor;

//commit the transaction

[CATransaction commit];

}

To run the program, you will find that when you press the button, the layer color instantly switches to the new value, instead of the smooth transition before the animation. What happened? Implicit animation seems to be disabled by the UIView associated layer.

Just imagine, if UIView’s properties are animated, then we should be able to notice when we modify it. So, if the UIKit is built on Core Animation (default to animate everything), then how is the implicit animation disabled by UIKit?

We know that the Core Animation usually makes animations for all the properties of the CALayer, which can be animated, but the UIView closes the properties of the associated layer. To better illustrate this point, we need to know how the implicit animation is implemented.

When we change the property, the CALayer automatically applies the animation called behavior, and when the CALayer property is modified, it will adjust the -actionForKey: method, passing the name of the property. The remaining operations are detailed in the CALayer header file, in essence, are the following steps:

Layer first checks whether it has a delegate, and whether the CALayerDelegate protocol specified by the -actionForLayer:forKey method. If so, call and return the result directly.

If you do not have a delegate, or delegate does not implement the -actionForLayer:forKey method, the layer then checks the actions dictionary that contains the attribute name corresponding to the behavior mapping. If the actions dictionary does not contain the corresponding property, the layer then searches for the property name in its style dictionary. Finally, if the corresponding behavior is not found in the style, then the layer will call the -defaultActionForKey: method that defines the behavior of each attribute.

So after a complete search over -actionForKey: or return empty (in this case will not have occurred, or object animation) corresponding to the CALayer CAAction protocol, finally take the results to the previous and current value of animation. This explains how UIKit disables the implicit Animation: each UIView acts as a delegate to the associated layer and provides a -actionForLayer:forKey implementation. When not in the implementation of an animation block, UIView returns nil to all the layers, but within the range of the block, it returns a non null value. We can use a demo to do a simple experiment:

Test UIView actionForLayer:forKey: implementation:

@interface ViewController ()

@property (nonatomic, weak) IBOutlet UIView*layerView;

@end

@implementation ViewController

– (void) viewDidLoad

{

[super viewDidLoad];

//test layer when outside of animation action block

NSLog (@ Outside:, [self.layerView actionForLayer:self.layerView.layer% @ “forKey:@” backgroundColor “]);

//begin animation block

[UIView beginAnimations:nil context:nil];

//test layer when inside of animation action block

NSLog (@ Inside:, [self.layerView actionForLayer:self.layerView.layer% @ “forKey:@” backgroundColor “]);

//end animation block

[UIView commitAnimations];

}

@end

Run the program, the console displays the results as follows:

$LayerTest[21215:c07] Outside: $LayerTest[21215:c07] Inside:

As a result, we can predict that when the property changes outside the animation block, the UIView directly disables the implicit animation by returning nil. However, in the animation block range, according to the specific type of animation to return the corresponding attributes, in this example is CABasicAnimation.

Of course, the return of nil is not the only way to disable implicit animation, CATransacition has a method called +setDisableActions:, can be used to open or close all of the attributes of the animation. If you add the following code in listing 7.2 [CATransaction begin], it will also prevent the occurrence of animation:

[CATransaction setDisableActions:YES];

To sum up, we know the following points

UIView Association layer disable implicit animation, the animation function is the only way to do this is to use the animation on the layer of UIView (rather than relying on CATransaction or UIView), inheritance, and overriding the -actionForLayer:forKey: method, or directly create an explicit animation.

For separate layers, we can control the implicit animation by implementing the -actionForLayer:forKey: delegate method of the layer, or by providing a actions dictionary.

Let’s use a different behavior for the color gradient example by setting up a custom actions dictionary for colorLayer. We can also use delegates to implement, but the actions dictionary can write less code. So how to create a suitable behavior object?

Behavior is usually an explicit animation object that is implicitly invoked by the Core Animation. Here we use an example of the realization of the CATransaction, called the push transition. For now, however, it is enough to know that the CATransition responds to the CAAction protocol and can act as a layer. The result is very good, regardless of when to change the background color, the new color is sliding from the left side, rather than the default gradient effect.

Custom behavior

@interfaceViewController ()

@property (nonatomic, weak) IBOutlet UIView*layerView;

@property (nonatomic, weak) IBOutlet CALayer*colorLayer;

@end

@implementation ViewController

– (void) viewDidLoad

{

[super viewDidLoad];

//create sublayer

Self.colorLayer =[CALayer layer];

Self.colorLayer.frame= CGRectMake (50.0f, 50.0f, 100.0f, 100.0f);

Self.colorLayer.backgroundColor=[UIColor blueColor].CGColor; //add a actionCATransition *transition =[CATransition custom animation];

Transition.type=kCATransitionPush;

Transition.subtype=kCATransitionFromLeft;

Self.colorLayer.actions= @{@ “backgroundColor”: transition};

//add it to our view

[self.layerView.layer addSublayer:self.colorLayer];

}

– (IBAction) changeColor

{//randomize the layer background color

CGFloat red = arc4random (/) / (CGFloat) INT_MAX;

CGFloat green= arc4random () / (CGFloat) INT_MAX;

CGFloat blue= arc4random () / (CGFloat) INT_MAX;

Self.colorLayer.backgroundColor= [UIColor green:green blue:blue colorWithRed:red alpha:1.0].CGColor;

}

@end

IOS let your App move
run effect diagram

Presentation and model

The behavior of CALayer is not normal, because changing the properties of a layer does not take effect immediately, but through a period of gradual update. How is this done?

When you change the attributes of a layer, the attribute value is indeed immediately updated (if you read it, you will find it set the value of it the moment you have in effect), but the screen does not immediately change. This is because the property you set does not directly adjust the appearance of the layer. Instead, it defines the appearance of the layer that will change after the end of the animation.

When setting the CALayer property, it is actually a model of how the layer is displayed after the end of the current transaction. The Core Animation acts as a controller and is responsible for updating the properties of the view on the screen according to the layer behavior and transaction settings.

We are talking about a typical mini MVC model. CALayer is a user interface (MVC) in the view of the fictional class, but in the context of the interface itself, the behavior of CALayer is more like a view of how to display and animation data model. In fact, in Apple’s own documents, the layer tree is usually a value of the layer tree model.

In iOS, the screen is redrawn 60 times per second. If the animation is longer than 60 seconds, Core Animation will need to re organize the layer on the screen by setting a new value and the new value. This means that in addition to the “true” value (the value you set), CALayer

Need to know the record of the current property value displayed on the screen.

The display values for each layer attribute are stored in a separate layer called the presentation layer, which can be accessed by the -presentationLayer method. The render layer is actually a copy of the model layer, but its attribute value represents the current appearance at any given time. In other words, you can get the true value displayed on the current screen by presenting the value of the layer.

We mentioned in Chapter 1, in addition to the layer tree, and the presentation tree. The render tree is formed by the presentation layer of all the layers in the layer tree. Note that the render layer is created only when the layer is first submitted (the first time it is shown on the screen), so that the call to -presentationLayer will return nil.

You may notice a method called modelLayer. Calling on the presentation layer – modelLayer will return it to render the CALayer. It is usually called -modelLayer on a layer – self (in fact, the original layer we have created is a data model).

IOS let your App move
how a mobile layer is represented by a data model

In most cases, you do not need to directly access the presentation layer, you can interact with the model layer, so that the Core Animation update display. In the two case, it is very useful to render the layer, one is the synchronized animation, the other is to handle the user interaction.

If you are in the realization of a timer based animation, and not just the transaction based animation, this time to know exactly in a moment in what position will be placed on the layer layer right very useful.

If you want your animation layers in response to user input, you can use the -hitTest: method to determine whether the specified layer is touched, at this time of presentation layer instead of calling the -hitTest: layer model would make more sense, because the presentation layer represents the user see the current layer position, and after the end of the animation is not the current position.

We can use a simple case to prove the latter. In this example, clicking anywhere on the screen will allow the layer to move there. Click on the layer itself to change its color. We call the -hitTest: by presenting the layer to determine whether it is clicked.

If you modify the code to make the -hitTest: work directly on the colorLayer instead of rendering the layer, you will find that it does not display correctly when the layer is moved. At this point you need to click on the layer to be moved to the location instead of the layer itself to respond to the click (which is why the presentation layer is used to respond to the interaction).

Use the presentationLayer layer to determine the current layer position

@interfaceViewController ()

@property (nonatomic, strong) CALayer*colorLayer;

@end

@implementation ViewController

– (void) viewDidLoad

{

[super viewDidLoad];

//create a red layer

Self.colorLayer =[CALayer layer];

Self.colorLayer.frame= CGRectMake (0,0100100);

Self.colorLayer.position= CGPointMake (self.view.bounds.size.width /2, self.view.bounds.size.height /2);

Self.colorLayer.backgroundColor=[UIColor redColor].CGColor;

[self.view.layer addSublayer:self.colorLayer];

}

– (void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event{

//get the touch point

CGPoint point =[[touches anyObject] locationInView:self.view];

//check if we ‘ve the moving tapped layer

If ([self.colorLayer.presentationLayer hitTest:point]) {

//randomize the layer background color

CGFloat red = arc4random (/) / (CGFloat) INT_MAX;

CGFloat green= arc4random () / (CGFloat) INT_MAX;

CGFloat blue= arc4random () / (CGFloat) INT_MAX;

Self.colorLayer.backgroundColor= [UIColor green:green blue:blue colorWithRed:red alpha:1.0].CGColor;

}else{

//otherwise (slowly) move layer to new the position

[CATransaction begin];

[CATransaction setAnimationDuration:4.0];

Self.colorLayer.position=point;

[CATransaction commit];

}

}

summary

In this chapter, we discuss the implicit animation, and the mechanism of Core Animation to select the appropriate animation behavior. At the same time, you know how UIKit makes full use of the implicit animation mechanism of Core Animation to enhance its explicit system and how it is disabled by default and enabled when needed. Finally, you learn how to render and model layers, and how Core Animation uses them to determine the current location and location of the layer.

Display animation:

The last chapter introduces the concept of implicit animation. Implicit animation is a direct way to create a dynamic user interface on the iOS platform, as well as the UIKit

The base of the system, but it does not cover all types of animation. In this chapter, we’ll look at explicit animation, which can specify custom animations for a number of properties, or create non-linear animations, such as

Arbitrary curve movement.

Attribute animation

First of all, we will explore the property animation. The property animation acts on a single attribute of the layer and specifies a target value for it, or a list of values that will be animated. Attribute animation can be divided into two types: basic and key frames.

Basic animation

Animation is actually a period of change, the simplest form is to change from one value to another value, which is the most important function of CABasicAnimation.

CABasicAnimation is a subclass of CAPropertyAnimation, CAPropertyAnimation is also an abstract base class for all types of animation in Core Animation. As an abstract class, CAAnimation itself does not do much work, it provides a timing function,

A delegate (used to back up the animation state) and a removedOnCompletion to identify whether the animation should be automatically released at the end (default YES, in order to prevent memory leaks).

CAAnimation also implements a number of protocols, including CAAction (allowing CAAnimation subclasses to provide layer behavior), as well as

CAMediaTiming. CAPropertyAnimation specifies the CAAnimation of a keyPath by specifying the keyPath of the animation acting on a single attribute, which is usually applied to a specified CALayer. In fact, it is a critical path (with some point object method can be in hierarchical relationship to any nested), rather than just the name of a property, because it means that the property animation can not only act on the layer itself, but also contains the attribute members of the child, and even some virtual attribute (we’ll explain why later.).

CAPropertyAnimation specifies the CAAnimation of a keyPath by specifying the keyPath of the animation acting on a single attribute, which is usually applied to a specified CALayer. In fact, it is a critical path (with some point object method can be in hierarchical relationship to any nested), rather than just the name of a property, because it means that the property animation can not only act on the layer itself, but also contains the attribute members of the child, and even some virtual attribute (we’ll explain why later.).

CABasicAnimation inherits from CAPropertyAnimation and adds the following properties:

ID fromValue

ID toValue

ID byValue

From the name can be a very good explanation: fromValue on behalf of the animation before the start of the value of the property, toValue represents the value of the end of the animation, byValue represents the animation to change the value of the implementation process.

By combining these three properties, there are many ways to specify an animation process. They are defined as ID types rather than specific types because the property animation can be used for many different types of attributes, including numeric types, vectors, transformation matrices, and even colors or images.

In the iOS, the display animation can be used to show the life of the film”. There are three major elements of the film: actor + script + shooting, the concept of analogy as follows:

Actor —> CALayer, who is the protagonist of the film

Script —> CAAnimation, how to set the film how to play, how to go, how to transform

Shooting —> AddAnimation, start execution

What is CAAnimation?

CAAnimation can be divided into four kinds:

1.CABasicAnimation

By setting the starting point, end point, and time, the animation moves along your fixed point. Can be seen as a special CAKeyFrameAnimation

2.CAKeyframeAnimation

Keyframe as the name suggests is the key point of the frame, you can set the starting point of the CALayer, the middle of the key points, the end of the frame, time, the animation will follow the trajectory you set to move

3.CAAnimationGroup

Group is also the meaning of the combination, that is, all of the Layer animation are combined. PS: a layer set up a lot of animation, they will be executed at the same time, how to execute in order I will say.

4.CATransition

This is apple to help developers packaged some of the animation

Two, hands-on work

Practice comes true, see an example to know:

For example, we want to achieve a similar heartbeat zoom animation can do so, divided into the actor initialization, set the script, the film shooting three steps:

IOS let your App move

effect, please refer to the blue box in the drawing. The other effect can be easily achieved yihuhuhuapiao. Want to achieve a different effect, the key lies in the initialization of the CABasicAnimation object in the keyPath settings. There are several different keyPath in iOS, which represent different effects:

IOS let your App move

In addition, we can also use GroupAnimation to achieve a combination of a variety of animation, the animation in the GroupAnimation type is the same.

IOS let your App move

Last run effect:

IOS let your App move

Bessel curve:

Use the UIBezierPath class to create a vector based path, which is in UIKit. This is a Core Graphics framework on the path package. Use this class to define a simple shape, such as an ellipse or a rectangle, or the shape of a number of lines and curves.

1.Bezier Path Foundation

The UIBezierPath object is the encapsulation of the CGPathRef data type. If the path is based on vector shapes, both the line and the line segment are created. We use a straight line to create a rectangle and a polygon, and use the curve to create an arc (ARC), circle, or other complex curve shape. Each section includes one or more points, and the drawing command defines how to interpret them. The end of each line or curve is the beginning of the next. The set of straight lines or curves of each connection becomes subpath. A UIBezierPath object defines a complete path that includes one or more subpaths.

The process of creating and using a path object is separate. Creating path is the first step, including the steps:

(1) to create a Bezier path object.

(2) use moveToPoint: to set the starting point of the initial line segment.

(3) add line or curve to define one or more subpaths.

(4) change the properties of the UIBezierPath object associated with the drawing.

For example, we can set the properties of the stroked lineWidth and lineJoinStyle path. You can also set the properties of the filled usesEvenOddFillRule path.

When creating the path, we should manage the points above the path with respect to the origin (0, 0), so that we can easily move the path later. In order to draw

Path object, we need to use the stroke and fill methods. These methods are in current graphic

Context rendering path under line and curve segment.

2, the use of UIBezierPath to create a polygon – add a straight line below the path polygon

Polygons are simple shapes that are made up of lines, and we can use moveToPoint: and addLineToPoint: methods to build them.

Method moveToPoint: set the starting point we want to create shapes. From this point, we can use addLineToPoint: to create a shape of the line segment.

We can continue to create line, each line is the starting point of the previous end, the end is the specified point.

The following code describes how to create a Pentagon with a line segment. The fifth line is obtained by calling the closePath method, which connects the last point (0, 40) and the first point (100, 0)

Description: the closePath method is not only the end of a shape subpath statement, it also draw a line between the last point and the first point, if we draw polygons, this is a convenient method we do not need to draw a line at the end.

Only override drawRect: / if you perform custom drawing.

An empty implementation / adversely affects performance during animation.

– (void) drawRect: (CGRect) rect

{

UIColor *color = [UIColor redColor];

[color set]; / / set the line color

UIBezierPath* aPath = [UIBezierPath bezierPath];

APath.lineWidth = 5;

APath.lineCapStyle = kCGLineCapRound; / / corner line

APath.lineJoinStyle = kCGLineCapRound; / / end point processing

Set the starting / point of the shape.

[aPath moveToPoint:CGPointMake (100, 0)];

Draw the lines /

[aPath addLineToPoint:CGPointMake (200, 40)];

[aPath addLineToPoint:CGPointMake (160, 140)];

[aPath addLineToPoint:CGPointMake (40, 140)];

[aPath addLineToPoint:CGPointMake (0, 40)];

[aPath closePath]; / / the fifth lines obtained by calling the closePath method

[aPath stroke] //Draws line; according to the coordinate point

}

Note: this class is inherited from UIView.

The results of the operation are as follows:

IOS let your App move

If you modify the last sentence Code: [aPathfill];

The results are as follows:

IOS let your App move

So you know the difference between stroke and fill method!

3, use UIBezierPath to create a rectangle

Use this method to:

Creates and returns anewUIBezierPath object initialized with a rectangular path.

+ (UIBezierPath *) bezierPathWithRect: (CGRect) rect

Demo code:

– (void) drawRect: (CGRect) rect

{

UIColor *color = [UIColor redColor];

[color set]; / / set the line color

UIBezierPath* aPath bezierPathWithRect:CGRectMake ([UIBezierPath = 20, 20, 100, 50)];

APath.lineWidth = 5;

APath.lineCapStyle = kCGLineCapRound; / / corner line

APath.lineJoinStyle = kCGLineCapRound; / / end point processing

[aPath stroke];

}

4, the use of UIBezierPath to create a circular or oval

Use this method to:

Creates and returns anewUIBezierPath object initialized with an oval path inscribed in the specified rectangle

+ (UIBezierPath *) bezierPathWithOvalInRect: (CGRect) rect

This method is based on the parameters of the rect rectangle to draw an internal curve.

When the incoming rect is a square, the image is an inscribed circle; when the incoming rect is a rectangle, the image is an inner ellipse.

5, the use of UIBezierPath to create a curve

Use this method:

Creates and returns anewUIBezierPath object initialized with an arc of a circle.

+ (UIBezierPath *) bezierPathWithArcCenter: (CGPoint) center radius: (CGFloat) radius startAngle: (CGFloat) startAngle endAngle: (CGFloat) endAngle clockwise: (BOOL) clockwise

Parameters

Center

Specifies the center point of the circle (in the current coordinate system used to define) the arc.

Radius

Specifies the radius of the circle used to define the arc.

StartAngle

Specifies the starting angle of the arc (measured in radians).

EndAngle

Specifies the end angle of the arc (measured in radians).

Clockwise

The direction in which to draw the arc.

Return Value

Anewpath object with the specified arc.

The parameters are specified: the center of the arc, the radius, the starting angle, the end angle, whether clockwise direction.

The following is the arc of the reference system.

IOS let your App move

Demo code:

#define PI 3.14159265359

#define DEGREES_TO_RADIANS (degrees) ((pi * degrees) / 180)

– (void) drawRect: (CGRect) rect

{

UIColor *color = [UIColor redColor];

[color set]; / / set the line color

UIBezierPath* aPath bezierPathWithArcCenter:CGPointMake ([UIBezierPath = 150, 150)

Radius:75

StartAngle:0

EndAngle:DEGREES_TO_RADIANS (135)

Clockwise:YES];

APath.lineWidth = 5;

APath.lineCapStyle = kCGLineCapRound; / / corner line

APath.lineJoinStyle = kCGLineCapRound; / / end point processing

[aPath stroke];

}

The results are as follows:

IOS let your App move

6, the UIBezierPath class provides support for adding the two Bessel curve and the three time of the Bessel curve.

The curve segment begins at the current point and ends at the specified point. The shape of a curve has a starting point, an end point, and a tangent definition of one or more control points. The following figure shows the similarity of the two types of curves and the relationship between the control points and the curve shape.

(1) drawing the two Bessel curve

Use this method:

Appends a quadratic B zier curve to the receiver ‘s path.

– (void) addQuadCurveToPoint: (CGPoint) endPoint controlPoint: (CGPoint) controlPoint

Parameters

EndPoint

The end point of the curve.

ControlPoint

The control point of the curve.

IOS let your App move

Demo code:

– (void) drawRect: (CGRect) rect

{

UIColor *color = [UIColor redColor];

[color set]; / / set the line color

UIBezierPath* aPath = [UIBezierPath bezierPath];

APath.lineWidth = 5;

APath.lineCapStyle = kCGLineCapRound; / / corner line

APath.lineJoinStyle = kCGLineCapRound; / / end point processing

[aPath moveToPoint:CGPointMake (20, 100)];

[aPath addQuadCurveToPoint:CGPointMake (120, 100) controlPoint:CGPointMake (70, 0)];

[aPath stroke];

}

IOS let your App move

(2) drawing the three Bessel curve

Use this method:

Appends a cubic B zier curve to the receiver ‘s path.

– (void) addCurveToPoint: (CGPoint) endPoint controlPoint1: (CGPoint) controlPoint1 controlPoint2: (CGPoint) controlPoint2

Parameters

EndPoint

The end point of the curve.

ControlPoint1

The first control point to use when computing the curve.

ControlPoint2

The second control point to use when computing the curve.

IOS let your App move

Demo code:

– (void) drawRect: (CGRect) rect

{

UIColor *color = [UIColor redColor];

[color set]; / / set the line color

UIBezierPath* aPath = [UIBezierPath bezierPath];

APath.lineWidth = 5;

APath.lineCapStyle = kCGLineCapRound; / / corner line

APath.lineJoinStyle = kCGLineCapRound; / / end point processing

[aPath moveToPoint:CGPointMake (20, 50)];

[aPath addCurveToPoint:CGPointMake (200, 50) controlPoint1:CGPointMake (110, 0) controlPoint2:CGPointMake (110, 100)];

[aPath stroke];

}

IOS let your App move

7 use the Core Graphics function to modify the path.

The UIBezierPath class is just a wrapper for the CGPathRef data type and the path drawing property. Although we can usually use

UIBezierPath class method to add straight line and curve line, UIBezierPath class also provides a property CGPath, we can use to modify the underlying path

Data type. If we want to create a path with the Core Graphics frame function, we want to use this property.

There are two ways to modify the UIBezierPath object associated with the path. Core can be fully used

Graphics function to modify the path, you can also use Core

Graphics function and UIBezierPath function mixed to modify. The first method is relatively easy in some ways. We can create a CGPathRef data type,

And call the function we need to modify the path information.

The following code is assigned a new CGPathRef to the UIBezierPath object.

The path data / / Create

CGMutablePathRef cgPath = CGPathCreateMutable ();

CGPathAddEllipseInRect (cgPath, NULL, CGRectMake (0, 0, 300, 300));

CGPathAddEllipseInRect (cgPath, NULL, CGRectMake (50, 50, 200, 200));

Create the UIBezierPath object / / Now

UIBezierPath* aPath = [UIBezierPath bezierPath];

APath.CGPath = cgPath;

APath.usesEvenOddFillRule = YES;

Assigning it to the UIBezierPath / After object, you can release

CGPathRef data type safely. / / your

CGPathRelease (cgPath);

If we use the Core Graphics function and the UIBezierPath function blending method, we must be careful to move the path information between the two. Because the UIBezierPath class has its underlying CGPathRef data type, we can’t simply retrieve the type and modify it directly. Instead, we should generate a copy, then modify the copy, and then assign this copy to the CGPath property, as follows:

Mixing Core Graphics andUIBezierPathcalls

UIBezierPath* aPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake (0, 0, 300, 300)];

Get the CGPathRef and create a / mutable version.

CGPathRef cgPath = aPath.CGPath;

CGMutablePathRef mutablePath = CGPathCreateMutableCopy (cgPath);

Modify the path and assign it / back to the UIBezierPath object

CGPathAddEllipseInRect (mutablePath, NULL, CGRectMake (50, 50, 200, 200));

APath.CGPath = mutablePath;

Release both the mutable copy of / the path.

CGPathRelease (mutablePath);

8.rendering (render) the contents of the Bezier Path object.

When a UIBezierPath object is created, we can use it’s stroke and fill methods to render it in current graphics context. Before calling these methods, we have to do some other tasks to ensure that the path.

Use the UIColor class method to go to stroke and fill want color.

Set the position of the shape in the target view. If we create the path relative to the origin (0, 0), then we can give current drawing

Context apply an appropriate affie

Transform. For example, I would like to drawing a shape start point in (0, 0), I can call the function CGContextTranslateCTM, and specify the horizontal and vertical

The translation value of the straight direction is 10. Adjust graphic

Context is the preferred method for adjusting path objects with respect to the points, since we can easily save and undo the previous graphics state.

Update the drawing property of the path object. When rendering path, the drawing property of the UIBezierPath instance overrides the property values under graphics context.

The following code is implemented in a custom view implementation of drawRect: method to draw an ellipse. The upper left corner of the rectangle is located at the point (50, 50) of the coordinate system.

Drawing a in a path view

(void) drawRect: (CGRect) rect

{

An oval shape to draw. / / Create

UIBezierPath* aPath = [UIBezierPath bezierPathWithOvalInRect:

CGRectMake (0, 0, 200, 100);

The render colors / / Set

[[UIColor blackColor] setStroke];

[[UIColor redColor] setFill];

CGContextRef aRef = UIGraphicsGetCurrentContext ();

If you have content to draw / after the shape,

Save the current state before changing / the transform

//CGContextSaveGState (aRef);

Adjust the view’s origin temporarily. The / oval is

Now drawn relative to the new / origin point.

CGContextTranslateCTM (aRef, 50, 50);

The drawing options as needed. / / Adjust

APath.lineWidth = 5;

Fill the path before stroking it / so that the fill

Color does not obscure the stroked / / line.

[aPath fill];

[aPath stroke];

Restore the graphics state before drawing / any other content.

//CGContextRestoreGState (aRef);

}

UIView package animation:

1 simple instructions

UIKit directly integrates the animation into the UIView class, and UIView will provide support for these changes when some of the properties are changed

The execution of the work required to complete the animation automatically by the UIView class, but still in the hope of notice views of animation, therefore need to change the attributes of code between [UIViewbeginAnimations:nilcontext:nil] and [UIViewcommitAnimations]

Common method analysis:

(void) + setAnimationDelegate: (ID) delegate animation set the proxy object, will send a message to the proxy object when the animation at the start or end

(void) + setAnimationWillStartSelector: (SEL) selector when the animation is about to begin, the implementation of the delegate object selector, and the beginAnimations:context: parameters in selector

(void) + setAnimationDidStopSelector: (SEL) selector when at the end of the animation, the implementation of the delegate object selector, and the beginAnimations:context: parameters in selector

(void) + setAnimationDuration: (NSTimeInterval) duration duration animation, seconds

(void) + setAnimationDelay: (NSTimeInterval) to start delay delay delay seconds

(void) + setAnimationStartDate: (NSDate * startDate) start time animation, the default is now

(void) + setAnimationCurve: (UIViewAnimationCurve) curve animation rhythm control

(void) + setAnimationRepeatCount: (float) repeatCount repeat number animation

(void) + setAnimationRepeatAutoreverses: (BOOL) repeatAutoreverses if set to YES, on behalf of the implementation of the effect of each repetition of animation will follow an opposite

(void) + setAnimationTransition: (UIViewAnimationTransition) transitionforView: (UIView *) viewcache: (BOOL) cache transition effect set the view of view, transition specifies the transition type, cache set YES representative view cache, good performance

2 code examples:

IOS let your App move

Implementation results:

IOS let your App move
IOS let your App move

Print animation block position:

IOS let your App move

The contrast between 3.UIView and CALayer animation

The use of UIView and CALayer are able to achieve animation effects, but in the real development, the general is still the main use of UIView packaging animation, and rarely use CALayer animation.

The difference between CALayer core animation and UIView animation:

UIView package will not rebound after the completion of the animation. That is, if it is through the CALayer core animation to change the position of the layer state, although the surface has changed, but in fact it is not changed position.

Code sample:

IOS let your App move

Print result:

IOS let your App move

Two, block animation

1 simple instructions

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

Parameter analysis:

Duration: duration of animation

Delay: animation delayed delay seconds after the start

Options: animation rhythm control

Animations: code that changes the view properties in this block

Completion: after the animation is finished, it will automatically call the block

Transition animation

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

Parameter analysis:

Duration: duration of animation

View: view of transition animation required

Options: type of transition animation

Animations: code that changes the view properties in this block

Completion: after the animation is finished, it will automatically call the block

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

After the method call is completed, it is equivalent to the following code:

/ / add toView to the parent view

[fromView.superview addSubview:toView];

/ / remove fromView from the parent view

[fromView removeFromSuperview];

Parameter analysis:

Duration: duration of animation

Options: type of transition animation

Completion: after the animation is finished, it will automatically call the block

2 code examples

IOS let your App move

Print result:

IOS let your App move

Tip: self.customView.layer.position and self.customView.center are equivalent because the default value for position is (0.5, 0.5).

Three, supplement

1.UIImageView frame animation

UIImageView allows a series of images to be displayed sequentially in a given time

Attribute analysis:

AnimationImages: the image to be displayed (a NSArray with UIImage)

AnimationDuration: full display of the time required for all images in a animationImages

AnimationRepeatCount: the number of times the animation has been executed (default is 0, representing an infinite loop)

Correlation analysis:

– (void) startAnimating; start animation

– (void) stopAnimating; Stop Animation

– (BOOL) isAnimating; is running animation

2.UIActivityIndicatorView

Is a rotating schedule, which can be used to inform the user that there is an operation in progress, usually with initWithActivityIndicatorStyle initialization

Analytical method:

– (void) startAnimating; start animation

– (void) stopAnimating; Stop Animation

– (BOOL) isAnimating; is running animation

UIActivityIndicatorViewStyle has 3 values to choose from:

UIActivityIndicatorViewStyleWhiteLarge / large white indicator

UIActivityIndicatorViewStyleWhite / / standard size white indicator

UIActivityIndicatorViewStyleGray / grey indicator for white background

Package transition animation:

.h code:

#import

#import

@interface ZciotAnimation: NSObject

(void) ZciotAnimation: (int) type ForView: (UIView *) view Subtype: (int) subtype BackgroundImage: (NSString *) image;

@end

.m code:

#import “ZciotAnimation.h”

#define DURATION 0.7f

Typedef enum: NSUInteger {

Fade = 1, / fade

Push, / / push

Reveal, / / open

MoveIn, / cover

Cube, / cube

SuckEffect, / suck

OglFlip, / Flip

RippleEffect, / bellows

PageCurl, / / page

PageUnCurl, / back flip

CameraIrisHollowOpen, / / open shots

CameraIrisHollowClose, / / close shot

CurlDown, / / next page

CurlUp, / / page

FlipFromLeft, / left turn

FlipFromRight, / rightTurn

} AnimationType;

@implementation ZciotAnimation

(void) ZciotAnimation: (int) type ForView: (UIView *) view Subtype: (int) subtype BackgroundImage: (NSString *) image

{

AnimationType animationType = type;

NSString *subtypeString;

Switch (subtype) {

Case 0:

SubtypeString = kCATransitionFromLeft;

Break;

Case 1:

SubtypeString = kCATransitionFromBottom;

Break;

Case 2:

SubtypeString = kCATransitionFromRight;

Break;

Case 3:

SubtypeString = kCATransitionFromTop;

Break;

Default:

Break;

}

/ / _subtype = 1;

If (_subtype / > 3) {

/ / _subtype = 0;

/ /}

Switch (animationType) {

Case Fade:

[self transitionWithType:kCATransitionFade WithSubtype:subtypeString ForView:view];

Break;

Case Push:

[self transitionWithType:kCATransitionPush WithSubtype:subtypeString ForView:view];

Break;

Case Reveal:

[self transitionWithType:kCATransitionReveal WithSubtype:subtypeString ForView:view];

Break;

Case MoveIn:

[self transitionWithType:kCATransitionMoveIn WithSubtype:subtypeString ForView:view];

Break;

Case Cube:

[self transitionWithType:@ “Cube” WithSubtype:subtypeString ForView:view];

Break;

Case SuckEffect:

[self transitionWithType:@ “suckEffect” WithSubtype:subtypeString ForView:view];

Break;

Case OglFlip:

[self transitionWithType:@ “oglFlip” WithSubtype:subtypeString ForView:view];

Break;

Case RippleEffect:

[self transitionWithType:@ “rippleEffect” WithSubtype:subtypeString ForView:view];

Break;

Case PageCurl:

[self transitionWithType:@ “pageCurl” WithSubtype:subtypeString ForView:view];

Break;

Case PageUnCurl:

[self transitionWithType:@ “pageUnCurl” WithSubtype:subtypeString ForView:view];

Break;

Case CameraIrisHollowOpen:

[self transitionWithType:@ “cameraIrisHollowOpen” WithSubtype:subtypeString ForView:view];

Break;

Case CameraIrisHollowClose:

[self transitionWithType:@ “cameraIrisHollowClose” WithSubtype:subtypeString ForView:view];

Break;

Case CurlDown:

[self animationWithView:view WithAnimationTransition:UIViewAnimationTransitionCurlDown];

Break;

Case CurlUp:

[self animationWithView:view WithAnimationTransition:UIViewAnimationTransitionCurlUp];

Break;

Case FlipFromLeft:

[self animationWithView:view WithAnimationTransition:UIViewAnimationTransitionFlipFromLeft];

Break;

Case FlipFromRight:

[self animationWithView:view WithAnimationTransition:UIViewAnimationTransitionFlipFromRight];

Break;

Default:

Break;

}

[self addBgImageWithImageName:image BackgroundView:view];

}

#pragma CATransition animation implementation

+ (void) transitionWithType: (NSString *) type WithSubtype: (NSString *) subtype ForView: (UIView *) view

{

/ / create a CATransition object

CATransition *animation = [CATransition animation];

/ / set exercise time

Animation.duration = DURATION;

Set / / type

Animation.type = type;

If (subtype! = Nil) {

/ / subclassing

Animation.subtype = subtype;

}

/ / set speed

Animation.timingFunction = UIViewAnimationOptionCurveEaseInOut;

[view.layer addAnimation:animation forKey:@ “animation”];

}

#pragma UIView animation

(void) animationWithView: (UIView *) view WithAnimationTransition (UIViewAnimationTransition) transition

{

[UIView animateWithDuration:DURATION animations:^{

[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

[UIView setAnimationTransition:transition forView:view cache:YES];

}];

}

#pragma add background to View

+ (void) addBgImageWithImageName: (NSString *) imageName BackgroundView: (UIView *) view

{

View.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:imageName]];

}

@end

After the package is good, you need to use the animation where the call API on the line:

IOS let your App move

Part animation effects:

IOS let your App move

Summary:

To this is basically introduced the end of the iOS animation, I will be free to the demo package github.

Reference excellent blog:

Http://www.cnblogs.com/wendingding/p/3802830.html

Http://www.mamicode.com/info-detail-500488.html

Http://www.cnblogs.com/moyunmo/p/3600091.html? Utm_source=tuicool& utm_medium=referral

Http://www.jianshu.com/p/8c1c1697c0ce

Http://www.cnblogs.com/wengzilin/p/4250957.html

Http://www.cocoachina.com/ios/20141226/10775.html

Blogger micro-blog, CocoaChina blog, CSDN blog sync updates, welcome attention:

Sina: http://weibo.com/p/1005052308506177/home? From=page_100505_profile& wvr=6& mod=data& is_all=1#place

CocoaChina:http://blog.cocoachina.com/477998

CSDN:http://blog.csdn.net/czkyes