lunedì 2 novembre 2009

Animated GIF using LWUIT

Since a couple of weeks ago, I'm working on moving my mobile applications to a new attractive user interface using LWUIT (LightWeigth User Interface Toolkit).
I found LWUIT really very impressive and the results are really excellent: my mobile apps now are much nicer then before.
But I found some little lacks in LWUIT. The most relevant is the lack of a class to manage animated GIF at runtime.
As of this writing, the current version of LWUIT supports animated gifs only if they are added in the resource file by the Resource Editor as "Animated Images". Such animated images can be added to a Label, to a Button or to another component and are animated when shown.
What I mean is that there are no way to use an animated GIF as animated image in a component if the gif is loaded at runtime from an input stream. Also, there is no way to manage the animation loop programmatically (i.e. stopping and starting the animation).
So, I googled a little to find a solution. First of all I found several posts related to that. This means that such a lack is involving several programmers. Second, I found the class GifDecoder ported to J2ME for decoding any animated gif.
Starting from that class and reading how the class StaticAnimation of LWUIT is implemented I wrote a new class AnimatedGIF, derived from the class com.sun.lwuit.Image, that allows to use animated gif at runtime in your applications.
You can use it as any other image.
The following is a snippet that shows how to create a Button with a animated gif image:

AnimatedGIF image = AnimatedGIF.createAnimatedGIF(
    new ByteArrayInputStream(btImage));
Button btn = new Button();

The source code can be downloaded from here and it is published under LGPL.
Mainly this is the most relevant topics:
- the package must be com.sun.lwuit because I need the costructor Image(Object) that has package visibility (I think it should have protected visibility)
- an animated gif is rapresented as an array of frames
- the frames are generated by the class GifDecoder
- a gif is animated if it has more then one frame
- the animation can be started and stopped on demand by the method start and stop
- the loop counter can be set by the method setLoopCount
- the rest of the code has been taken and adapted from the class StaticAnimation

For more info about LWUIT visit this url