Let your images explode in J2ME!

After a MIDP 1.0 utility to rotate images now time has come for some image fun :)

J2ME Image explode effect screenshot
When writing mobile applications, it’s always cool to add some effects or transitions. But, while for example FlashLite has a nice builtin support for them, with J2ME you have to hand-code even the simplest movement (and this is the main reason why most J2ME apps are all but attractive).

So, here’s a first class that you can use to add an “explode” effect to images in a straightforward way. How to do it? Here we come:

  1. Download the ExplodingImage.java source code and put it straight in your project
  2. Instantiate an ExplodingImage this way:
    //get your Image
    Image sourceImage = Image.createImage("/image.png");
    //and then use it in ExplodingImage constructor
    ExplodingImage image = new ExplodingImage(sourceImage , 5, 8, 8);

    The ExplodingImage constructor accepts the following arguments:

    • An Image instance
    • An int representing the “level” for the exploding effect, that is the strength of the effect itself (higher the level, stronger the effect).
    • The last 2 int arguments represent the horizontal and vertical pieces of the exploded image.
  3. Start the explode effect with the explode() method, that will accept the effect duration as argument:
    image.explode(2000L);
  4. To paint it, simply use its paint() method, very similary to the Graphics drawImage() one. For example, in a Canvas paint() method, you can do something like this:
    protected void paint(Graphics g)
    {
    	g.setColor(0xffffff);
    	g.fillRect(0, 0, width, height);
    	image.paint(g, getWidth() / 2, getHeight() / 2, Graphics.HCENTER | Graphics.VCENTER);
    }

    To give the effect a “smooth” animation, you should paint it quite frequently (let’s say, not once per second :)). So, always using Canvas, a sample code could be like this:

    public void run()
    {
    	while(true)
    	{
    		repaint();
     
    		try
    		{
    			synchronized(this)
    			{
    				wait(50L);
    			}
    		}
    		catch(Exception e)
    		{
    			e.printStackTrace();
    		}
    	}
    }
  5. To test if the effect has ended, you can simply access your ExplodingImage ended instance variable:
    if(image.ended)
    {
    	//effect-end related code
    }
  6. And you’re done! See it in action here: J2ME image explode effect in action

Sample source code is available here:

Be Sociable, Share!