Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 實現仿心跳動畫效果的方法

編輯:關於 Android 程式設計

本文透過實例,講解如何在 Android 中實作類似心臟跳動的縮放動畫效果。

核心做法是把「放大並變淡」與「縮回並還原」兩個動畫串接起來,形成一來一回的節奏,模擬心跳的收縮與舒張:

 // 按鈕模擬心髒跳動 private void playHeartbeatAnimation() { AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(new ScaleAnimation(1.0f, 1.8f, 1.0f, 1.8f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)); animationSet.addAnimation(new AlphaAnimation(1.0f, 0.4f)); animationSet.setDuration(200); animationSet.setInterpolator(new AccelerateInterpolator()); animationSet.setFillAfter(true); animationSet.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(new ScaleAnimation(1.8f, 1.0f, 1.8f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)); animationSet.addAnimation(new AlphaAnimation(0.4f, 1.0f)); animationSet.setDuration(600); animationSet.setInterpolator(new DecelerateInterpolator()); animationSet.setFillAfter(false); // 實現心跳的View imageView.startAnimation(animationSet); } }); // 實現心跳的View imageView.startAnimation(animationSet); } 

由於這是一個持續循環的動畫,需要開一個執行緒來驅動。當然還有另一種做法,就是在動畫結束時啟動下一段動畫,如此交替也能達到同樣效果;這裡的範例採用的是執行緒的方式:

 new Thread(){ public void run() { while (true){ try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } runOnUiThread(new Runnable() { public void run() { playHeartbeatAnimation(); } }); } }; }.start(); 

要特別注意的是,動畫的更新必須在 UI 執行緒上進行,因此範例中透過 runOnUiThread 來觸發動畫,避免直接在其他執行緒操作 View 造成異常。希望本文所述能對大家的 Android 程式設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved