[Android] 21.3 animation and android21.3 Animation

Source: Internet
Author: User

[Android] 21.3 animation and android21.3 Animation

Category: C #, Android, VS2015;

Created on: 1. Introduction

Android provides the following three ways to create an animation:

  • Drawable Animations-canvas animation, also called Frame animation ).
  • View Animations-View animation, also known as Tween Animations ).
  • Property Animations-Property animation. Available from Android 3.0.

Note: although these three types of animations are available, attribute animation should be used as a priority if possible. In addition, although the animation can attract people, do not abuse it, otherwise it will only be counterproductive.

1. Drawing Board animation (Drawable Animations)

Drawable Animations provides a simple animation API for Frame-based playback. In other implementations, it is generally referred to as Frame animation ). The playing effect of this animation is very similar to that of a movie or cartoon.

Frame animations produce animation effects by playing images in sequence. You can play Six images in sequence to achieve the animation effects of a person jumping up:

The canvas resources (XML files) that control the animation sequence are usually stored in the/Resource/drawable folder of the application. The <animation-list> element is used as the root element in the file, use the <item> element to define each frame.

For example, define an animation sequence in the/Resource/drawable/ch2103DrawableAnimDemo. xml file:

<Animation-list xmlns: android = "http://schemas.android.com/apk/res/android">

<Item android: drawable = "@ drawable/a01" android: duration = "100"/>

<Item android: drawable = "@ drawable/a02" android: duration = "100"/>

<Item android: drawable = "@ drawable/a03" android: duration = "100"/>

<Item android: drawable = "@ drawable/a04" android: duration = "100"/>

<Item android: drawable = "@ drawable/a05" android: duration = "100"/>

<Item android: drawable = "@ drawable/a06" android: duration = "100"/>

</Animation-list>

The animation contains six frames. Among them, a01 ~ A06 is an image file. The android: duration Attribute declares the display time of each frame. After defining the animation sequence, you only need to specify the file in the layout file, Android will automatically load and display the animation in order.

2. View animation)

In the Android system, view animation (or complementary animation) has four manifestations: gradient, scaling, translation, and rotation. View animation can be used to complete a series of simple changes, such as position, size, opacity, and rotation. For example, animation processing is performed on an ImageView in the program.

View Animation is located in the namespace of Android. View. Animation. In the code, you can use the following method to Animation the View object:

AlphaAnimation: animation class that controls opacity changes

Rotate Animation: controls the rotation of an Animation class

ScaleAnimation: an animated class that controls scaling changes

TranslateAnimation: animation class that controls translation changes

AnimationSet: Set class that controls animation attributes

Animation conversion files are generally stored in the/Resources/anim folder. In addition, although this API was provided in earlier versions, it is still useful due to its simplicity.

Note: The XML file saved in the/Resources/anim folder is the preferred method for declaring View animations, because this method is easier to read and maintain. The XML file must use one of the following elements as the root element:

  • Alpha-Fade-in or fade-out animation
  • Rotate-rotating Animation
  • Scale-zoom Animation
  • Translate-translation (horizontal or vertical motion)
  • Set-animation container, which can accommodate one or more other animation Elements

By default, Android will apply all animations in the XML file at the same time. To change the animation in the specified order, set the android: startOffset attribute to one of the elements defined above.

You can also use the interpolation tool to change the animation speed, such as acceleration, repetition, deceleration, and other animation effects:

  • AcclerateInterpolator/DecelerateInterpolator-increase or decrease the animation Rate
  • BounceInterpolator-rebound at animation end
  • LinearInterpolator-constant rate

For detailed usage, see "view animation example" in this example ". In this example, the animation first scales the image along the horizontal and vertical directions, and then rotates the image 45 degrees counter-clockwise to reduce the image size.

3. Property Animation)

This animation can process attributes of any object (including views). It is the preferred method for executing an animation, even if the animation object is invisible.

The flexibility of the property animation API is that it can also encapsulate animations in different classes, making code sharing more convenient.

All property animations are created through an instance of the Animator subclass:

  • ValueAnimator-this is the most important class in the property animation API. It automatically calculates the attribute values to be modified. Instead of directly modifying these values, the animation object is updated with events.
  • ObjectAnimator-Animations a certain attribute of the target object.
  • AnimationSet-This class is used to save an animation set, which can be used in a program to "execute at the same time, execute in sequence, and execute in a delayed manner.

If you use an animation, you may also need the following special classes:

  • IntEvaluator-calculate the integer property value
  • FloatEvaluator-calculate the Floating Point Property Value
  • ArgbEvaluator-calculate the color type Attribute Value

If the animation processing attributes are not float, int, or Color, you can use the ITypeEvaluator interface to create your own computing type.

(1) ValueAnimator

You can obtain an instance of ValueAnimator by calling one of the following methods:

  • ValueAnimator. OfInt
  • ValueAnimator. OfFloat
  • ValueAnimator. OfObject

The following code demonstrates how to animation a value from 0 to 100. The animation duration is 1000 milliseconds.

ValueAnimator animator = ValueAnimator. OfInt (0,100 );

Animator. SetDuration (1000 );

Animator. Start ();

However, these codes are not enough because the animation is executed but the target is not updated to a new value. Therefore, related events need to be introduced:

MyCustomObject myObj = new MyCustomObject ();

MyObj. SomeIntegerValue =-1;

Animator. Update + = (object sender, ValueAnimator. AnimatorUpdateEventArgs e) =>

{

Int newValue = (int) e. Animation. AnimatedValue;

// Apply this new value to the object being animated.

MyObj. SomeIntegerValue = newValue;

};

(2) ObjectAnimator

ObjectAnimator is a subclass of ViewAnimator. It combines the timing engine and ValueAnimator to implement animation. For example:

MyCustomObject myObj = new MyCustomObject ();

MyObj. SomeIntegerValue =-1;

ObjectAnimator animator = ObjectAnimator. OfFloat (myObj, "SomeIntegerValue", 0,100 );

Animator. SetDuration (1000 );

Animator. Start ();

Compared with the previous code, this can reduce the amount of code. Ii. Example

1. Run

2. Design Steps

(1) Add Images

Under the drawablefolder, add 6 images (ch2103asteroid01.png ~ Ch2103asteroid06.png). These images are used to demonstrate Frame Animation usage.

Then upload a ch2103ship.png image to demonstrate the usage of view animation.

(2) Add ch2103DrawableAnimDemo. xml

Add the file in the Resources/Drawable folder.

<?xml version="1.0" encoding="UTF-8" ?><animation-list xmlns:android="http://schemas.android.com/apk/res/android" >  <item android:drawable="@drawable/ch2103asteroid01" android:duration="100" />  <item android:drawable="@drawable/ch2103asteroid02" android:duration="100" />  <item android:drawable="@drawable/ch2103asteroid03" android:duration="100" />  <item android:drawable="@drawable/ch2103asteroid04" android:duration="100" />  <item android:drawable="@drawable/ch2103asteroid05" android:duration="100" />  <item android:drawable="@drawable/ch2103asteroid06" android:duration="100" /></animation-list>

(3) add ch2103ViewAnimDemo. xml

Add the file in the Resources/anim folder.

<?xml version="1.0" encoding="utf-8" ?><set xmlns:android="http://schemas.android.com/apk/res/android"     android:shareInterpolator="false">  <scale android:interpolator="@android:anim/accelerate_decelerate_interpolator"         android:fromXScale="1.0"         android:toXScale="1.4"         android:fromYScale="1.0"         android:toYScale="0.6"         android:pivotX="50%"         android:pivotY="50%"         android:fillEnabled="true"         android:fillAfter="false"         android:duration="700" />  <set android:interpolator="@android:anim/accelerate_interpolator">    <scale android:fromXScale="1.4"           android:toXScale="0.0"           android:fromYScale="0.6"           android:toYScale="0.0"           android:pivotX="50%"           android:pivotY="50%"           android:fillEnabled="true"           android:fillBefore="false"           android:fillAfter="true"           android:startOffset="700"           android:duration="400" />    <rotate android:fromDegrees="0"            android:toDegrees="-45"            android:toYScale="0.0"            android:pivotX="50%"            android:pivotY="50%"            android:fillEnabled="true"            android:fillBefore="false"            android:fillAfter="true"            android:startOffset="700"            android:duration="400" />  </set></set>

(4) add ch2103Main. axml

Add the file in the Resources/layout folder.

<? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: orientation = "vertical" android: layout_width = "match_parent" android: layout_height = "match_parent" android: minWidth = "25px" android: minHeight = "25px"> <TextView android: text = "canvas animation example" android: textAppearance = "? Android: attr/textAppearanceSmall "android: layout_width =" fill_parent "android: layout_height =" wrap_content "android: gravity =" center "android: background =" @ color/myGray "android: layout_marginTop = "5dp"/> <ImageView android: src = "@ android: drawable/ic_menu_gallery" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: id = "@ + id/ch2103_imageView_DrawableDemo" android: layout_margin Top = "5dp"/> <TextView android: text = "view animation example" android: textAppearance = "? Android: attr/textAppearanceSmall "android: layout_width =" fill_parent "android: layout_height =" wrap_content "android: gravity =" center "android: background =" @ color/myGray "android: layout_marginTop = "5dp"/> <ImageView android: src = "@ android: drawable/ic_menu_gallery" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: id = "@ + id/ch2103_imageView_ViewDemo" android: layout_marginLeft = "20dp" android: layout_marginTop = "5dp"/> <Button android: text = "" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: id = "@ + id/ch2103_btnViewDemoStart" android: layout_gravity = "center"/> <TextView android: text = "Property animation example (drag and drop a slider to observe the progress bar animation)" android: textAppearance = "? Android: attr/textAppearanceSmall "android: layout_width =" fill_parent "android: layout_height =" wrap_content "android: gravity =" center "android: background =" @ color/myGray "android: layout_marginTop = "5dp"/> <FrameLayout android: minWidth = "25px" android: minHeight = "35px" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: id = "@ + id/frameLayout1" android: layout_marginTop = "15dp" android: layout_marginBottom = "5dp"> <MyDemos. srcDemos. ch2103MyView android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: layout_marginLeft = "8dp" android: layout_marginRight = "8dp" android: id = "@ + id/ch2103myview1"/> </FrameLayout> <SeekBar android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: id = "@ + id/ch2103seekBar1" android: max = "100" android: progress = "50" android: layout_marginLeft = "8dp" android: layout_marginRight = "8dp" android: layout_marginTop = "10dp"/> </LinearLayout>

(5) add ch2103MyView. cs

Using System; using Android. content; using Android. views; using Android. graphics; using Android. util; using Android. animation; namespace MyDemos. srcDemos {// <summary> // demonstrate the basic usage of progress bar animation control /// </summary> public class ch2103MyView: View {private const int DefaultHeight = 20; private const int DefaultWidth = 120; private Paint mNegativePaint; private double mPosition = 0.5; private Paint mPositivePaint; p Ublic ch2103MyView (Context context, IAttributeSet attrs): this (context, attrs, 0) {Initialize ();} public ch2103MyView (Context context, IAttributeSet attrs, int defStyle ): base (context, attrs, defStyle) {Initialize ();} public double CurrentValue {get {return mPosition;} set {mPosition = Math. max (0f, Math. min (value, 1f); Invalidate () ;}} public void SetCurentValue (double value, bool anim Ate) {if (! Animate) {CurrentValue = value; return;} ValueAnimator animator = ValueAnimator. ofFloat (float) mPosition, (float) Math. max (0f, Math. min (value, 1f); animator. setDuration (500); animator. update + = (sender, e) => CurrentValue = (double) e. animation. animatedValue; animator. start ();} protected override void OnDraw (Canvas canvas) {base. onDraw (canvas); float middle = canvas. width * (float) mPosition; ca Nvas. drawPaint (mNegativePaint); canvas. drawRect (0, 0, middle, canvas. height, mPositivePaint);} protected override void OnMeasure (int widthMeasureSpec, int heightMeasureSpec) {int width = MeasureSpec. getSize (widthMeasureSpec); SetMeasuredDimension (width <DefaultWidth? DefaultWidth: width, DefaultHeight);} private void Initialize () {mPositivePaint = new Paint {AntiAlias = true, Color = Color. rgb (0x99, 0xcc, 0),}; mPositivePaint. setStyle (Paint. style. fillAndStroke); mNegativePaint = new Paint {AntiAlias = true, Color = Color. rgb (0xff, 0x44, 0x44)}; mNegativePaint. setStyle (Paint. style. fillAndStroke );}}}

(6) add ch2103MainActivity. cs

Using Android. app; using Android. OS; using Android. widget; using Android. views. animations; namespace MyDemos. srcDemos {[Activity (Label = "[Example 21-3] animation basic usage")] public class ch2103MainActivity: Activity {protected override void OnCreate (Bundle savedInstanceState) {base. onCreate (savedInstanceState); SetContentView (Resource. layout. ch2103Main); // canvas animation Demo var img1 = FindViewById <ImageView> (Resource. id. ch2103_imageView_DrawableDemo); img1.SetImageResource (Resource. drawable. ch2103DrawableAnimDemo); // view animation Demo var btn1 = FindViewById <Button> (Resource. id. ch2103_btnViewDemoStart); btn1.Click + = (sender, args) ==>{ Animation animation = AnimationUtils. loadAnimation (this, Resource. animation. ch2103ViewAnimDemo); var img2 = FindViewById <ImageView> (Resource. id. ch2103_imageView_ViewDemo); img2.SetImageResource (Resource. drawable. ch2103ship); img2.StartAnimation (animation) ;}; // property animation Demo var myView = FindViewById <ch2103MyView> (Resource. id. ch2103myview1); var seekBar = FindViewById <SeekBar> (Resource. id. ch2103seekBar1); seekBar. stopTrackingTouch + = (sender, args) => {double currentValue = (double) seekBar. progress)/seekBar. max; myView. setCurentValue (currentValue, true );};}}}

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.