Tutorial #30: Create Animation in Android

Hello everyone!

It’s difficult to find time these days. However, I always try and make sure that the learning never stops! In one of my earlier posts I had talked about displaying, storing and resizing of Images in Android. In this tutorial, I will talk about creating an animation using the Animation resources offered by Android.

Android includes an Animation class using which an animation can be applied to Views, Surfaces or other objects. There are basically two main types of Animations:

1. Property Animation ( android.animation)

The property animation system allows developers to animate object properties of any type, for example, int, float. One can also specify keyframes, group animations and even control the behavior of animations.

2. View Animation ( android.view.animation )

Unlike property animation, View animation is used to create simple animations such as tweened animation and frame by frame animation. Tweened animation creates an animation by performing a series of transformations on a single image where as frame by frame animation creates an animation by showing a sequence of images.

Once the above concepts are clear, we can now proceed towards creating a simple fade in/fade out animation in Android.

Pre-requisites: Eclipse IDE (preferably latest version), Android SDK

Open the Eclipse IDE. Create a new Android Project named AndroidAnimationDemo with Target SDK Android 2.3.3. Let the package name be com.example and choose to create a Blank Activity.

Step 1: Create anim folder to include Animation

Expand your Project under the Package explorer window. You will find a folder named res. Inside the res folder, create a new folder named anim.

Now, create two XML files as follows:

res/anim/anim_fade_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
  android:interpolator="@android:anim/linear_interpolator">
  <alpha
      android:fromAlpha="0.1"
      android:toAlpha="1.0"
      android:duration="2000"/>
</set>

res/anim/anim_fade_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
  android:interpolator="@android:anim/linear_interpolator">
  <alpha
      android:fromAlpha="1.0"
      android:toAlpha="0.1"
      android:duration="2000"/>
</set>

As you can see, we can achieve the fade in and fade out animations by merely changing the alpha (toAlpha and fromAlpha) values. Depending upon your requirements you can also change the duration of the animation. An AlphaAnimation is used to represent a fade in or fade out animation. More details can be found over here.

Step 2: Write Activity code

Moving on, open your Activity class and add the following code!

MainActivity.java

package com.example;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity
 {
	
	private ImageView image;
	private Animation animFadeIn;
	private Animation animFadeOut;
	private Button btnFadeIn;
	private Button btnFadeOut;
	
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
    
      btnFadeIn = (Button)findViewById(R.id.btn_fadein);
      btnFadeOut = (Button)findViewById(R.id.btn_fadeout);
      image = (ImageView)findViewById(R.id.my_image);
    
      animFadeIn = AnimationUtils.loadAnimation(this, R.anim.anim_fade_in);
      btnFadeIn.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    image.startAnimation(animFadeIn);
   }});
    
      animFadeOut = AnimationUtils.loadAnimation(this, R.anim.anim_fade_out);
      btnFadeOut.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    image.startAnimation(animFadeOut);
   }});
  }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >
 
  <Button
      android:id="@+id/btn_fadein"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="Fade In"/>
  <Button
      android:id="@+id/btn_fadeout"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="Fade Out"/>
  
 <LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical"
     android:gravity="center">

 <ImageView
     android:id="@+id/my_image"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:src="@drawable/android" />
   
 </LinearLayout>  

</LinearLayout>

I have added a sample JPG image in my drawable folder. No changes are required to the AndroidManifest.xml file. Run the project on the emulator and you should see the following output! Source code can be found over here.

Output

android_animation_2

Learning Kivy: Animate widgets

Hello everyone!

The Kivy framework provides the kivy.animation module to animate widgets. For any animation, we must specify certain values that represent the position of the animated object.

To use Animation in Kivy one needs to follow two simple steps namely:

1. Setup an Animation object
2. Use the Animation object on a Widget

There are two kinds of Animation that can be applied:

1. Sequential Animation

As the name suggests, it is used to join animations sequentially using the ‘+’ operator.

Example from Kivy docs:

anim = Animation(x=50) + Animation(size=(80, 80), duration=2.)
anim.start(widget)

The above example will animate to x=50 over 1 second, then animate size to (80, 80) over the next two seconds.

2. Parallel Animation

It is used join animations in parallel. It uses the ‘&’ operator.

Example from Kivy docs:

anim = Animation(pos=(80, 10))
anim &= Animation(size=(800, 800), duration=2.)
anim.start(widget)

The above example will animate position to (80, 10) over 1 second, while in parallel animating the first half of size=(800, 800).

Along with animations one can also use various Animation Transition properties to create custom animations for widgets. One can use built-in or custom transition functions using transition (or t= shortcut).

For example using the ‘in_quad’ transition as follows:

anim = Animation(x=50, size=(80, 80), t='in_quad')
anim.start(widget)

Here is a sample program to demonstrate the Animation module in Kivy:


import kivy
kivy.require('1.4.0')

from kivy.app import App
from kivy.uix.button import Button
from kivy.animation import Animation
from kivy.uix.widget import Widget

class MyAnimApp(App):

        def build(self):
            parent= Widget()
            button= Button(text='Animated', font_size=14)
            button.bind(on_press=self.on_button_press)
            parent.add_widget(button)
            return parent
          
        def on_button_press(self,instance):
            anim = Animation(x=50, size=(50, 50), t='in_out_bounce')
            #apply sequential animation
            anim += Animation(pos=(200,70),t='in_out_back')
            #apply parallel animation
            anim &= Animation(size=(100,50))
            anim.start(instance)
                        

if __name__== '__main__':
       MyAnimApp().run()

You can write the above code using the Python IDLE and run it as:

kivy yourfilename.py

Tutorial #8: Creating an animation using Processing

Hello everyone,

In one of my earlier posts I had talked about Processing and the features it offers to developers using two sample programs. At the end I had promised to bring out certain more features. This post of mine tells you how to create your own animation using Processing!

For creating an animation we would require a model. I will be using custom wavefront object (.obj) models. These models can be created using any of the popular 3D modelling software out there, say Blender or 3ds Max. For this tutorial I will be using a Superman model made by the developer of AndAR which happens to be a popular augmented reality project for Android.

The Superman model can be downloaded from here. The material file (.mtl) for the same can be downloaded from over here.

Let’s proceed with the tutorial now!

First start the Processing application. By default a Sketch will be created and you can begin writing your code in the Editor. Make sure you have Java mode selected (seen at the right hand side of the toolbar).

Step 1: Add the model, background image and a float variable

PShape superman;
PImage bg;
float ry;

Step 2: Setup your screen


public void setup() 
{
  size(800, 600, P3D);
  frameRate(30);
  bg = loadImage("background.jpg");
  superman = loadShape("superman3.obj");
 
}

Note: The files background.jpg ; .obj file and the .mtl file of your model should be present inside the data folder of your project.

Step 3: Once the screen is setup, add the draw method

public void draw() 
{
  
   background(bg);  //add the background image
   lights();        
   translate(width/2, height/2, -200);  //keep the model at the center of the screen or window
   rotateZ(PI);
   rotateY(ry);
   shape(superman);  //add the model
   ry+=0.2; 
  
   if(mousePressed) 
   {
    scale(2.0);    //increase size of model
    ry=0;
    translate(mouseX,mouseY, -200);
    shape(superman);
   } 
    
}

So that doest it! Here is the entire code:

PShape superman;
PImage bg;
float ry;
  
public void setup() 
{
  size(800, 600, P3D);
  frameRate(30);
  bg = loadImage("background.jpg");
  superman = loadShape("superman3.obj");
 
}

public void draw() 
{
  
   background(bg); 
   lights();  
   translate(width/2, height/2, -200);
   rotateZ(PI);
   rotateY(ry);
   shape(superman);
   ry+=0.2;
   
   if(mousePressed) 
   {
    scale(2.0);
    ry=0;
    translate(mouseX,mouseY, -200);
    shape(superman);
   } 
    
}

Run the application and you should see a rotating Superman model:

Screenshot

Now try pressing and moving your mouse. You should see an enlarged version of the superman model inside the screen. Hence, Processing is a tool that allows you create such animations and even more complex ones. Use your creativity and then there is no stopping you! 🙂