基於Java的動畫編程基礎(一)

來源:互聯網
上載者:User

基本技術:

在Java中實現動畫有很多種辦法,但它們實現的基本原理是一樣的,即在螢幕上畫出一系列的幀來造成運動的感覺。

我們先構造一個程式的架構,再慢慢擴充,使之功能比較齊備。

使用線程:

為了每秒中多次更新螢幕,必須建立一個線程來實現動畫的迴圈,這個迴圈要跟蹤當前幀並響應周期性的螢幕更新要求。實現線程的方法有兩種,你可以建立一個類Thread的衍生類別,或附和在一個Runnable的介面上。

一個容易犯的錯誤是將動畫迴圈放在paint()中,這樣佔據了主AWT線程,而主線程將負責所有的繪圖和事件處理。

一個架構applet如下:

public
  class Animator1 extends java.applet.Applet implements Runnable {
   int frame;
   int delay;
   Thread animator;
   public void init() {
    String str = getParameter("fps");
    int fps = (str != null) ? Integer.parseInt(str) : 10;
    delay = (fps > 0) ? (1000 / fps) : 100;
   }
   public vois start() {
    animator = new Thread(this);
    animator.start();
   }
   public void run() {
    while (Thread.currentThread() == animator) {
     repaint();
     try {
      Thread.sleep(delay);
     } catch (InterruptedException e) {
      break;
     }
    frame++;
   }
  }
  public void stop() {
   animator = null;
  }
 }

在你的HTML檔案中這樣引用:

<applet code=Animator1.class width=200 height=200>
<param name=fps value=200>
</applet>

上面的參數fps表示每秒的幀數

保持恒定的幀速度:

上例中,applet只是在每兩幀之間休眠一個固定的時間,但這有些缺點,有時你會等很長時間,為了每秒顯示十幀圖象,不應該休眠100毫秒,因為在運行當中也耗費了時間。

這裡有一個簡單的補救方法:

public void run() {
long tm = System.currentTimeMillis();
while (Thread.currentThread() == animator) {
repaint();
try {
tm += delay;
Thread.sleep(Math.max(0,tm -
System.currentTimeMillis()));
} catch (InterruptedException e) {
break;
}
frame++;
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.