程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> J2ME >> 用J2ME在移動設備上實現動畫

用J2ME在移動設備上實現動畫

編輯:J2ME
應用MIDP(Mobile Information Device Profile)的開發職員經常會埋怨用些什麼措施才可以在一個MIDlet上顯示動畫。MIDP 1.0 沒有直接供給對動畫的支撐(MIDP 2.0支撐),但真要是自己往實現,實在也並非是一件很難的事。 

  任何動畫的最基礎的條件,是要在足夠快的時間內顯示和調換一張張的圖片,讓人的眼睛看到動的畫面後果。圖片必需按照次序畫出來。從一張圖片到下一張圖片之間的變更越小,後果會越好。 

  首先要做的,是應用你的圖片處理軟件(比如ps或者firework)創立一系列雷同大小的圖片來組成動畫。每張圖片代表動畫一幀。你需要制作必定數目標祯--越多的幀會讓你的動畫看上往越平滑。制作好的圖片必定要保留成PNG(Portable Network Graphics)格局,MIDP唯一支撐的圖片格局。 

  有兩個措施讓你剛做好的圖片在MIDlet上變成動畫。第一,把圖片都放到一個web服務器上,讓MIDlet下載他們,MIDP內置的HTTP支撐。第二個措施更簡略,把圖片用MIDlet打包成jar文件。假如你應用的是J2ME開發工具,把PNG文件放你的項目文件裡面就可以了。 

  動畫的過程實在更像帳本記錄:顯示當前幀,然後適當地調換到下一幀。那麼應用一個類來完成這個工作應當是很適當的,那好,我們就先定義一個AnimatedImage類: 

import Java.util.*;import Javax.microedition.lcdui.*; //定義了一個動畫,該動畫實在只是Image[] images) { this(null, images, null); }  // Construct an animation with a null clip list.  public AnimatedImage(Canvas canvas, Image[] images) { this(canvas, images, null); }  // Construct an animation. The canvas can be null, // but if not null then a repaint will be triggered // on it each time the image changes due to a timer // event. If a clip list is specifIEd, the image is // drawn multiple times, each time with a different // clip rectangle, to simulate transparent parts.  public AnimatedImage(Canvas canvas, Image[] images, int[][] clipList) { this.canvas = canvas; this.images = images; this.clipList = clipList;  if (images != null && clipList != null) { if (clipList.length < images.length) { throw new IllegalArgumentException(); } }  if (images != null && images.length > 0) { w = images[0].getWidth(); h = images[0].getHeight(); } }  // Move to the next frame, wrapping if necessary.  public void advance(boolean repaint) { if (++current >= images.length) { current = 0; }  if (repaint && canvas != null && canvas.isShown()) { canvas.repaint(x, y, w, h); canvas.serviceRepaints(); } }  // Draw the current image in the animation. If // no clip list, just a *** copy, otherwise // set the clipping rectangle accordingly and // draw the image multiple times.  public void draw(Graphics g) { if (w == 0 || h == 0) return; int which = current; if (clipList == null || clipList[which] == null) { g.drawImage(images[which], x, y, g.TOP | g.LEFT); } else { int cx = g.getClipX (); int cy = g.getClipY(); int cw = g.getClipWidth(); int ch = g.getClipHeight();  int[] list = clipList[which];  for (int i = 0; i + 3 <= list.length; i += 4) { g.setClip(x + list[0], y + list[1], list[2], list[3]); g.drawImage(images[which], x, y, g.TOP | g.LEFT); }  g.setClip(cx, cy, cw, ch); } }  // Moves the animation´s top left corner.  public void move(int x, int y) { this.x = x; this.y = y; }  // Invoked by the timer. Advances to the next frame // and causes a repaint if a canvas is specifIEd.  public void run() { if (w == 0 || h == 0) return;  advance(true ); }}

  你實例化一個AnimatedImage對象的時候你必需給AnimatedImage類的結構方法傳一個Image對象數組,該數組代表動畫的每一幀。應用的所有圖片必需具有雷同的高度和寬度。 

  用Image.createImage()方法從jar文件裡面加載圖片: 

private Image[] loadFrames( String name, int frames )throws IOException {    Image[] images = new Image[frames];    for( int i = 0; i < frames; ++i ){        images = Image.createImage( name + i +".png" );    }    return images;}
  你也可以傳遞一個Canvas對象(可選),和一個剪輯列表(clip list)。假如你指定了一個canvas和應用一個timer來主動調換到動畫的下一幀,就如下面的例子代碼中一樣,canvas在動畫向前轉動以後主動被重畫(repaint)。不過這樣的實現措施是可選的,你可以這樣做,也可以讓程序選擇合適的時候重畫canvas。 

  由於MIDP 1.0不支撐透明的圖片,AnimatedImage 類應用一個剪輯列表來模仿透明的後果,剪輯列表是圖片被剪成的方塊區域的系列。圖片被畫出來的時候離開幾次,每次畫一個剪輯列表裡面的剪輯區域。剪輯列表在幀的基礎上被定義好,所以你需要為圖片的每一幀創立一個數組。數組的大小應當是4的倍數,由於每一個剪輯面積保持了四個數值:左坐標,頂坐標,寬度以及高度。坐標的原點是全部圖片的左上角。需要留心的是應用了剪輯列表會使動畫慢下來。假如圖片更加復雜的話,你應當應用矢量圖片。 

  AnimatedImage類擴大了Java.util.TimerTask,答應你設定一個timer。這裡有個例子闡明如何應用timer做動畫: 

Timer timer = new Timer();AnimatedImage ai = ..... // get the imagetimer.schedule
 ( ai, 200, 200 );

   每隔大約200毫秒,timer調用AnimatedImage.run()方法一次,這個方法使得動畫翻滾到下一個幀。現在我們需要的是讓MIDlet來試試顯示動畫!我們定義一個簡略的Canvas類的子類,好讓我們把動畫“粘貼上往”。 

import Java.util.*;import Javax.microedition.lcdui.*; //A canvas to which you can  protected void paint(Graphics g) { Graphics saved = g;  if (offscreen != null) { g = offscreen.getGraphics(); }  g.setColor(255, 255, 255); g.fillRect(0, 0, getWidth(), getHeight());  int n = images.size(); for (int i = 0; i < n; ++i) { AnimatedImage img = (AnimatedImage) images.elementAt(i); img.draw(g); }  if (g != saved) { saved.drawImage(offscreen, 0, 0, Graphics.LEFT | Graphics.TOP); } }}

AnimatedCanvas 類的代碼相當簡略,由一個動畫導進方法和一個paint方法。canvas畫布每次被畫,背景都會被擦除然後循環每個導進的AnimatedImage對象,直接畫到自己身上來(自己擴大了canvas類)。

import Java.io.*;import Java.util.*;import Javax.microedition.lcdui.*;import Javax
; //MIDlet that displays some *** animations.//Displays a serIEs of birds on the screen and//animates them at different (random) rates. public class AnimationTest extends MIDlet implements CommandListener {  private static final int BIRD_FRAMES = 7; private static final int NUM_BIRDS = 5;  private Display display; private Timer timer = new Timer(); private AnimatedImage[] birds; private Random random = new Random();  public static final Command exitCommand = new Command("Exit", Command.EXIT, 1);  public AnimationTest() { }  public void commandAction(Command c, Displayable d) { if (c == exitCommand) { exitMIDlet(); } }  protected void destroyApp(boolean unconditional) throws MIDletStateChangeException { exitMIDlet(); }  public void exitMIDlet() { timer.cancel(); // turn it off... notifyDestroyed(); }  // Generate a non-negative random number...  private int genRandom(int upper) { return (Math.abs(random.nextInt()) % upper); }  public Display getDisplay() { return display; }  // Initialize things by creating the canvas and then // creating a serIEs of birds that are moved to // random locations on the canvas and attached to // a timer for scheduling.  protected void initMIDlet() { try { AnimatedCanvas c = new AnimatedCanvas(getDisplay()); Image[] images = loadFrames("/images/bird", BIRD_FRAMES);  int w = c.getWidth(); int h = c.getHeight();  birds = new AnimatedImage[NUM_BIRDS]; for (int i = 0; i < NUM_BIRDS; ++i) { AnimatedImage b = new AnimatedImage(c, images); birds = b; b.move(genRandom(w), add(b); timer.schedule(b, genRandom(1000), genRandom(400)); }  c.addCommand(exitCommand); c.setCommandListener(this);  getDisplay().setCurrent(c); } catch (IOException e) { System.out.println("Could not load images"); exitMIDlet(); } }  // Load the bird animation, which is stored as a // serIEs of PNG files in the MIDlet suite.  private Image[] loadFrames(String name, int frames) throws IOException { Image[] images = new Image[frames]; for (int i = 0; i < frames; ++i) { images = Image.createImage(name + i + ".png"); }  return images; }  protected void pauseApp() { }  protected void startApp() throws MIDletStateChangeException { if (display == null) { display = Display.getDisplay(this); initMIDlet(); } }}

  七幀圖片的動畫,你可以看到一個拍著翅膀的小鳥。MIDlet顯示了5只小鳥,小鳥的地位和刷新速度是隨機的。你可以用一些其他的措施來改良這個程序,但這個程序也應當足夠能讓你上手了。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved