Monday, January 16, 2012

Android: Pendulum Animation

I am working on the splash screen for Monkey Write, and I would like the monkey to be swinging on a vine. In Android you can specify all kinds of animations with xml, so it took me a little bit of time to figure out all the perimeters. Here is my final swinging.xml:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
  android:fromDegrees="15"
  android:toDegrees="-15"
  android:pivotX="50%"
  android:pivotY="0%"
  android:duration="2000"
  android:repeatMode="reverse"
  android:repeatCount="-1"
/>

I am using a pivoted rotation to implement the swinging effect. The animation goes from 15 degrees to -15 degrees, but instead of pivoting at the center, I want the pivot point to be at the top-middle. This is achieved by pivotX="50%" and pivotY="0%". For non-stop animation, I use repeatCount="-1".

It was fairly straightforward figure out all those parameters. But the monkey swings from the left to right, then jumps back to the left before swinging again. To make him swing back and forth, I need to set the repeatMode to reverse. Now I have a properly swinging monkey!

I have uploaded my code here: http://github.com/chiuki/android-pendulum-animation. Instead of a monkey, I use xml to specify a pendulum, which seems appropriate for the animation.

2 comments:

Inline coding questions will not be answsered. Instead, ask on StackOverflow and put the link in the comment.

  1. Hello :)

    Very helpful example thanks a lot. One question that i want to use this as a rope and also want the rope to be a bit flexible then what i had to do?

    Love and Respect from Pakistan :)

    ReplyDelete
    Replies
    1. To make it look like a rope, you can replace the "pendulum" LinearLayout with an ImageView showing an png of a rope. Making it flexible will probably involve real physics, and I'm afraid the stock animation won't be able to simulate that.

      Delete