IOS development-from UIView Animation

Source: Internet
Author: User

IOS development-from UIView Animation

Beyond all doubt: in iOS development, animation effects are one of the most enjoyable aspects for developers. A well-designed and refined animation effect can give users a fresh and refreshing effect, attracting their eyes-this is very important for apps.

As the first part of the animation collection, this article was originally intended to explain how to create a drop-down and refresh water drop animation by qq. However, I have studied iOS Animations by Tutorials over the past few days, I have a deep understanding of iOS animation development, so I decided that the animation article will start with UIView animation, and there will be layers, Transitioning and other animations in the future, the following is a demo in the book.

Animation

Put the demo in this article first: click here
Ps: This is a beginner's animation getting started article.

Starting with the login Animation

For a long time, I have been performing animations Based on the CALayer layer, but ignored the animation interfaces provided by UIKit. These interface functions are powerful and flexible enough to meet the animation requirements of most of our development.

Before learning about these powerful interfaces, let's take a look at the first effect: when a user opens an app to log on, the account and password input boxes will enter from the left side of the screen, the logon button appears.

Interface Animation


The most obvious thing that occurs in this animation is the location change of the two text boxes. Before the animation starts, the positions of the two text boxes should be on the left of the screen, the buttons below are hidden (set alpha)

Before the animation starts


Therefore, we can use the following code to summarize what happens in this animation:

Self. userName. center. x + = offset; // userName enters self. password. center. x + = offset; // enter self with password. login. alpha = 1; // The logon button is displayed.

Now that we know what happened to our animation, we can useUIKitThe animation API makes our animation alive.

// Set the initial position of the text box to CGPointaccountCenter = self on the left of the screen. userName. center; CGPointpsdCenter = self. password. center; accountCenter. x-= 200; pasCenter. x-= 200; self. userName. center = accountCenter; self. password. center = psdCenter; // restore the center Coordinate accountCenter. x ++ = 200; psdCenter. x ++ = 200; [UIViewanimateWithDuration: 0.5 animations: ^ {self. userName. center = accountCenter; self. password. center = passwordCenter; self. login. alpha = 1 ;}completion: nil];

In UIKit, the system providesanimateHeadersUIViewThe class method allows us to easily make the animation effect, each of which provides a class method namedanimationsOfblockCode block. The code is executed in an animated manner immediately or after the method is called. In addition, the first parameter of all these Apis is used to set the animation duration.

InviewDidAppear:You can see that the text box slides from the left side, and the buttons are gradually displayed, but the results are not the same as what we want-the three animations are not staggered, the effect is not so nice. We hope that the password box will appear after a period of sliding in the account text box, and the button will also need to be displayed later. Therefore, we need to use the following method to achieve this effect:

[UIViewanimateWithDuration: 0.5 delay: 0.35 options: UIViewAnimationOptionCurveEaseInOutanimations: ^ {self. password. center = passwordCenter;} completion: ^ (BOOLfinished) {[UIViewanimateWithDuration: 0.2 animations: ^ {self. login. alpha = 1 ;}];

This method looks very familiar. Compared to the above method, there are several more parameters here to highly customize our Animation:

Duration: animation duration

Delay: determines how long the animation will be executed after the delay

Options: used to determine how an animation is displayed.

Animations: Code converted into an animated Representation

Completion: the code block executed after the animation ends.

In the above Code, the password input box starts to come out from the left after a delay of 0.35 seconds. After the animation lasts for 0.5 seconds, the gradient display button starts and the animation is completed.

Animation attributes

Now you can make simple animations, but remember that not all attributes modification operations are placed inanimationsCode blocks are all animated-no matter how you modify a viewtag, Ordelegate. Therefore, animation attributes can be implemented, which will inevitably lead to re-rendering of views.
These attributes that can generate an animation can be roughly divided into three types:Coordinate size,View display,Morphological changes

Coordinate dimensions

Bounds: When you modify this attributecenterAttribute re-calculationframe. We recommend that you use this attribute to modify the size.

Frame: modifying this attribute will usually cause the view to be moved while deformation occurs, and then reset it.centerAndboundsAttribute

Center: After setting, the view is moved to a new location.boundsRecalculateframe


Dimension modification View display class

BackgroundColor: modifying this attribute will produce the effect of color gradient transition. Essentially, the system constantly modifies tintColor to implement this function.

Alpha: modifying this attribute will produce a fade-in and fade-out effect.

Hidden: you can modify this attribute to hide pages.


Change transparency

Morphological changes

Transform: This attribute can be modified to achieve rotation, deformation, movement, flip, and other animation effects. It is implemented through matrix operations, so it is more powerful.


Rotating Animation Parameters

The animation method we used above has an important parameter.optionsIt allows you to customize animation effects in height. The following shows a set of values of this parameter type. You can use different parameters to achieve your own animation:

Repeating

UIViewAnimationOptionRepeat // The animation is cyclically executed. UIViewAnimationOptionAutoreverse // After the animation is executed, the animation is executed in reverse direction.

We will pass these two parameters into the above Password box to see what the effect will be (different parameters use|Operator)

[UIViewanimateWithDuration: 0.5 delay: 0.35 options: UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeatanimations: ^ {self. password. center = passwordCenter;} completion: ^ (BOOLfinished) {[UIViewanimateWithDuration: 0.2 animations: ^ {self. login. alpha = 1 ;}];
Repeated Animation


We can see that the password box is continuously circulating into the screen, exit the screen in the opposite direction, and the logon button does not appear gradually. From this we can know thatUIViewAnimationOptionRepeatThe Parameter not only enables loop playback of the animation, but also causescompletionThe callback will never be executed.

Easing
We all know that a good animation should be more in line with our cognitive rules. For example, nothing can suddenly start to move and stop. For example, a vehicle starts and stops a process of acceleration and deceleration.


Acceleration speed reduction of vehicles. PNG


In order to make the animation more in line with our cognition, the system also provides parameters with similar effects for us to use:

UIViewAnimationOptionCurveEaseInOut // accelerate and then slow down. The default value is UIViewAnimationOptionCurveEaseIn // from slow to fast. UIViewAnimationOptionCurveEaseOut // UIViewAnimationOptionCurveLinear // constant speed

I created four orange uiviews in the demo, passed in these four different parameters, and moved the four views up on the Y axis at the same time.

[SelfanimatedView: _ view1]; [selfanimatedView: _ view2]; [selfanimatedView: _ view3]; [selfanimatedView: _ view4]; // move the view up by 250 on the Y axis-(void) animatedView :( UIView *) view {[UIViewanimateWithDuration: 0.5 delay: 0 options: UIViewAnimationOptionCurveLinearanimations: ^ {CGPointcenter = view. center; center. y-= 250; view. center = center;} completion: nil];}
Four linear velocity representations


In the simulator running status, click the menu bar aboveDEBUG -> Slow AnimationOr shortcut keycommand + TThis slows down the animation running speed of our app (the demo runs on a 6 p simulator ).
In the deceleration environment, we can see the speed changes of the four views as follows:
1. acceleration.EaseIn
2. Acceleration first, and then deceleration.EaseInOut
3. Speed leads, and then slows down.EaseOut
4. Constant motion.Linear
Run the initial logon animation to slow down the animation speed of the simulator. You will seeEaseInOutThe parameter causes an animation to slow down when the Password box is close to the end point.

Transitioning
In addition to the effects mentioned above, when switching between views and images, we can also pass in the following parameters to implement some special animation effects.

UIViewAnimationOptionTransitionNone // no effect, default reverse // reverse from left effect preview // flip from right UIViewAnimationOptionTransitionCurlUp // flip from top to bottom UIViewAnimationOptionTransitionCurlDown // flip from bottom to bottom until the previous view is dissolved to the next view preview/ /flip from top effect UIViewAnimationOptionTransitionFlipFromBottom // flip from Top Effect

When will these parameters be used? Let's take a look at this piece of code:

[UIViewtransitionWithView: firstPVduration: 0.5 options: parameters: ^ {[firstPVflipCard];} completion: ^ (BOOLfinished) {isAnimating = NO ;}];-(void) flipCard {if (isfliped) {self. image = [UIImageimageNamed: @ "flipPicBG.png"]; isfliped = NO;} else {self. image = [UIImageimageNamed: [NSStringstringWithFormat: @ "flippicd.d.png", type]; isfliped = YES ;}}

In this Code, I changedUIImageViewThe image is also displayed in an animation. A new animation API method is used here,transitionWithView: duration: options: animations: completion:, This method keeps up with the followinganimateWithDurationThe series method has one moreUIViewType parameter. The object received by this parameter is used as the animation operator. This code is a game I used to perform card translation matching. The animation effect after clicking it is as follows:


Card translation matching games


Use in simulatorscommand+TAfter slowing down the animation speed, I captured the four flipped pictures:


Slow flip


When switching an image, the original image will be flipped over the X axis based on the central position of the view, in order to achieve more realistic results, the system also adds a shadow effect to the switchover, you should only use the transition animation in the view switch-you will not generate any transition effect in the Movement)

Spring Animation

Congratulations, you can useUIKitBy combining differentoptionsYou can make real animations for parameters. However, we can always do more. For example, if a spring is squashed by force, the spring will repeat when it is released. Even though the above method can be used to implement such an animation, the amount of code is complicated and there is basically no reusability. It can be imagined that it would be a bad code. Therefore, we need other animation methods. The system also provides such an animation for our use:

+ (Void) animateWithDuration :( NSTimeInterval) durationdelay :( NSTimeInterval) equal :( CGFloat) velocityoptions :( UIViewAnimationOptions) equal :( void (^) (void )) animationscompletion :( void (^__ nullable) (BOOLfinished) completion

Additional parameter information:

DampingRatio: the ratio of speed attenuation. Value Range: 0 ~ 1. The lower the value, the stronger the vibration.

Velocity: initialization speed. The higher the value, the faster the item is.

When a rounded corner button moves into the interface at a high speed, it will definitely attract your attention. For example, if I tryUICollectionViewWhen the category button is displayed in the view from the bottom of the screen; or I want this ball to the bottom right corner to prompt the user how to operate:

  • Ball pop-up effect


    This effect is very good. After you see these small balls, you will naturally want to click these buttons, and the animation popped up by these balls only requires the following code:

    CGPointcenter = cell. center; CGPointstartCenter = center; startCenter. y + = LXD_SCREEN_HEIGHT; cell. center = startCenter; [UIViewanimateWithDuration: 0.5 delay: 0.35 * indexPath. itemusingSpringWithDamping: 0.6 initialSpringVelocity: 0 options: UIViewAnimationOptionCurveLinearanimations: ^ {cell. center = center;} completion: nil];

    In addition to the pop-up Code, when the ball is clicked, an animation is generated in the lower right corner, and the list is displayed from the left. This is very cool, because no additional prompts are required, the user will naturally know how to return to the grouping interface-click the circular button in the lower right corner. This is very important. Our animation should not only be used to make the interface more elegant and beautiful, but also be used to reduce the cost of learning to use the app. These are the pursuit of animation.

    Last

    Compared with the rough PC end, mobile applications need to be more refined, and exquisite and complex animations are derived from a combination of simple animations. As the first blog of the animation article, this article aimsUIViewStarting with animation, we will gradually expand other animations and hope to play a role in attracting others. At the end of the article, if you are a beginner of iOS animation, please try to combine the knowledge above to add code to the logon demo at the beginning of this article, so that the button will pop up from the gradient below:

    The pop-up logon button

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.