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

用自定義 View 打造帶阻尼彈性效果的 Android 加載動畫

編輯:關於 Android 程式設計

先來看看最終呈現的動態效果:

動手之前需要具備的基礎知識:

1. 二次貝塞爾曲線

2. 動畫相關知識

3. 自定義 View 的基本用法

什麼是阻尼運動?

阻尼振動指的是:由於振動系統受到摩擦力、介質阻力或其他能量損耗的影響,振幅會隨時間逐漸衰減,因此也被稱為減幅振動或衰減振動。無論是彈簧振子還是單擺,外界的摩擦與介質阻力始終存在,振動過程中系統不斷克服阻力做功、消耗能量,振幅便會越來越小,經過一段時間後徹底停止。由於振幅與振動能量密切相關,阻尼振動本質上就是能量持續流失的過程。它屬於非簡諧運動,也屬於耗散系統。這裡所說的阻尼,是指任何振動系統在運動中因外界作用或自身固有原因而導致振幅逐步下降的特性,以及對這一特性的量化描述。

本例中文字的下凹起伏正是这种效果的直观体现,接下來就帶大家一步步動手實現。

跳動水果效果的實現思路

拆解一下:從效果圖可以看到,圖案從頂端向下墜落、再向上彈起,整個過程伴隨旋轉即可。

首先,我們自定義一個繼承自 FrameLayout 的 View:

 public class My extends FrameLayout { public My(Context context) { super(context); } public My(Context context, AttributeSet attrs) { super(context, attrs); } }

本例需要準備以下三張素材圖片:



或許有人會疑惑:效果圖中圖案到達頂部或底部時方向就反了,僅靠三張圖夠用嗎?

答案是:到達頂部或底部時只需旋轉 180 度即可,無需額外素材。

接著在自定義類中定義若干關鍵變量:

 //用於記錄當前圖片使用數組中的哪張 int indexImgFlag = 0; //下沉圖片 前面三個圖片的id int allImgDown [] = {R.mipmap.p2,R.mipmap.p4,R.mipmap.p6,R.mipmap.p8}; //動畫效果一次下沉或上彈的時間 animationDuration*2=一次完整動畫時間 int animationDuration = 1000; //彈起來的圖片 ImageView iv; //圖片下沉高度(即從最高點到最低點的距離) int downHeight = 2; //掉下去的動畫 private Animation translateDown; //彈起動畫 private Animation translateUp; //旋轉動畫 private ObjectAnimator rotation;

再來看看初始化動畫的方法。這裡採用了遞歸思路,讓動畫能夠無限循環播放,值得細細品味:

 //初始化彈跳動畫 public void MyAnmation(){ //下沉效果動畫 translateDown = new TranslateAnimation( Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0, Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,downHeight); translateDown.setDuration(animationDuration); //設置一個插值器 動畫將會播放越來越快 模擬重力 translateDown.setInterpolator(new AccelerateInterpolator()); //上彈動畫 translateUp = new TranslateAnimation( Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0, Animation.RELATIVE_TO_SELF,downHeight,Animation.RELATIVE_TO_SELF,0 ); translateUp.setDuration(animationDuration); ////設置一個插值器 動畫將會播放越來越慢 模擬反重力 translateUp.setInterpolator(new DecelerateInterpolator()); //當下沉動畫完成時播放啟動上彈 translateDown.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { iv.setImageResource(allImgDown[indexImgFlag]); rotation = ObjectAnimator.ofFloat(iv, "rotation", 180f, 360f); rotation.setDuration(1000); rotation.start(); } @Override public void onAnimationEnd(Animation animation) { iv.startAnimation(translateUp); } @Override public void onAnimationRepeat(Animation animation) { } }); //當上移動畫完成時 播放下移動畫 translateUp.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { indexImgFlag = 1+indexImgFlag>=allImgDown.length?0:1+indexImgFlag; iv.setImageResource(allImgDown[indexImgFlag]); rotation = ObjectAnimator.ofFloat(iv, "rotation", 0.0f, 180f); rotation.setDuration(1000); rotation.start(); } @Override public void onAnimationEnd(Animation animation) { //遞歸 iv.startAnimation(translateDown); } @Override public void onAnimationRepeat(Animation animation) { } }); }

這段代碼涉及一個關鍵概念——插值器(Interpolator),它能讓動畫在播放過程中的某段時間加快或減慢節奏。

//設置一個插值器 動畫將會播放越來越快 模擬重力

1.translateDown.setInterpolator(new AccelerateInterpolator());

這個加速插值器的速率曲線如下圖所示:

從曲線斜率不難看出,採用此插值器後動畫會越跑越快,正好用來模擬下落過程中重力的加速效果。

////設置一個插值器 動畫將會播放越來越慢 模擬反重力

2. translateUp.setInterpolator(new DecelerateInterpolator());

減速插值器的速率曲線如下:

最後,把圖片控件初始化到自定義 View 中:

 private void init() { //初始化彈跳圖片 控件 iv = new ImageView(getContext()); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); iv.setLayoutParams(params); iv.setImageResource(allImgDown[0]); this.addView(iv); iv.measure(0,0); iv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (!flagMeure) { flagMeure =true; //由於畫文字是由基准線開始 path.moveTo(iv.getX()-textWidth/2+iv.getWidth()/2, textHeight+iv.getHeight()+downHeight*iv.getHeight()); //計算最大彈力 maxElasticFactor = (float) (textHeight / elastic); //初始化貝塞爾曲線 path.rQuadTo(textWidth / 2, 0, textWidth, 0); //初始化上彈和下沉動畫 MyAnmation(); iv.startAnimation(translateDown); } } }); }

這裡有兩個容易踩坑的知識點:

 1. iv.measure(0,0);主動通知系統去測量此控件 不然iv.getwidth = 0; //下面這個是同理 等iv測量完時回調 不然iv.getwidth = 0; 2. iv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){ … }

原因很簡單:無論是 new TextView() 還是通過 LayoutInflater 填充布局,都是異步進行的,所以你在創建或填充完成後立刻取值,自然會拿到 0。

做到這一步,你只需要在自定義 View 的 onSizeChanged 回調中調用 init(),就能看到圖案的彈跳動畫了。

 @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); init(); }

該方法會在 onMeasure 執行完畢後回調,此時你就能安全地獲取自定義 View 的寬高了。

效果如下:

讓文字呈 U 形排布

要實現這個效果,先得補一點基礎知識——貝塞爾曲線。

本例用到的是二次貝塞爾曲線,我們先來直觀認識一下它:

 

曲線由三個點決定:p0 為起點、p1 為控制點、p2 為終點,透過貝塞爾公式即可畫出如圖所示的平滑曲線。

至於具體的推導過程,這裡不必深究,它需要一定的數學基礎,用到時直接調用 API 即可。

那麼在 Android 中如何繪製呢?

 Path path = new Path(); //p0的x y坐標 path.moveTo(p0.x,y); path.rQuadTo(p1.x,p1.y,p2.x,p2.y);

是不是非常簡單?接著只要在 dispatchDraw 或 onDraw 方法中把它畫出來即可:

 @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); canvas.drawPath(path,paint); }

這樣畫出的效果,跟在 PS 中用鋼筆工具勾出來的曲線幾乎一致——實際上 PS 的鋼筆工具背後正是二次貝塞爾曲線。

 

(此處借用一張示意圖)

如果三個點的相對位置與開頭那張圖一致(p1 位於 p0 右上方,同時又在 p2 左上方),那麼在屏幕上的顯示效果如下:

 

順帶談談 dispatchDraw 與 onDraw 的區別

如果你的自定義 View 直接繼承自 View,那麼繪製順序是先 onDraw 再 dispatchDraw。

而如果繼承自 ViewGroup,則會跳過 onDraw,直接調用 dispatchDraw——這一點要特別留意!本例中我們繼承的是 FrameLayout,而 FrameLayout 又源自 ViewGroup,所以走的是後者。

回到主題:如何畫出 U 形文字?思路很簡單,就是讓文字沿著我們畫好的曲線排布。比如要呈現「CSDN 開源中國」幾個字,怎樣讓它們緊貼曲線書寫呢?

這裡要介紹一個 API

canvas.drawTextOnPath()

 

第一個參數:要繪製的文字,類型為字符串。

第二個參數:路徑,也就是前面提到的二次貝塞爾曲線。

第三個參數:文字沿路徑起始位置的偏移量。

第四個參數:文字相對路徑的高度偏移量。

hOffset:

The distance along the path to add to the text's starting position

vOffset:

The distance above(-) or below(+) the path to position the text
//ok我們看看他可以畫出什麼樣子的文字

具體能畫出什麼樣的效果,取決於你對貝塞爾曲線的理解深度——理解越透徹,能創作的圖形就越豐富,當然也不一定非要局限於貝塞爾曲線。

確定貝塞爾曲線的起點

回過頭再看一眼效果圖:

可以發現,文字正好位於 iv(彈跳圖片)中央,且恰好落在 iv 彈到底部的位置。

在正式計算之前,先補充一點文字測量的知識,看下面這張圖:

當我們調用畫文字的 API(canvas.drawTextOnPath 或 canvas.drawText)時,繪製是以基線(baseline)為起點的,也就是圖中的 baseline。

舉個例子:

canvas.drawText("FMY",0,0,paint);

這樣寫你幾乎看不到文字,屏幕上只會露出文字的底部,如下圖:

另一個 API drawTextOnPath 也是同樣的道理。

再看幾個實用的小 API

1. paint.measureText("FMY"); 返回當前畫筆 paint 下 "FMY" 文字的寬度。

下面的 API 會把文字相對於左、上、右、下的邊界值寫入矩形,那麼:

 rect.right-rect.left=文字寬度 rect.bottom-rect.top=文字高度 //矩形 Rect rect = new Rect(); //將文字畫入矩形目的是為了測量高度 paint.getTextBounds(printText, 0, printText.length(), rect);

請看完整實現:

 private void init() { //初始化彈跳圖片 控件 iv = new ImageView(getContext()); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); iv.setLayoutParams(params); iv.setImageResource(allImgDown[0]); this.addView(iv); //畫筆的初始化 paint = new Paint(); paint.setStrokeWidth(1); paint.setColor(Color.CYAN); paint.setStyle(Paint.Style.FILL); paint.setTextSize(50); paint.setAntiAlias(true); //矩形 Rect rect = new Rect(); //將文字畫入矩形目的是為了測量高度 paint.getTextBounds(printText, 0, printText.length(), rect); //文本寬度 textWidth = paint.measureText(printText); //獲得文字高度 textHeight = rect.bottom - rect.top; //初始化路徑 path = new Path(); iv.setX(getWidth()/2); iv.measure(0,0); iv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (!flagMeure) { flagMeure =true; //由於畫文字是由基准線開始 path.moveTo(iv.getX()-textWidth/2+iv.getWidth()/2, textHeight+iv.getHeight()+downHeight*iv.getHeight()); //計算最大彈力 maxElasticFactor = (float) (textHeight / elastic); //初始化貝塞爾曲線 path.rQuadTo(textWidth / 2, 0, textWidth, 0); //初始化上彈和下沉動畫 MyAnmation(); iv.startAnimation(translateDown); } } }); }

接著寫一個方法,在 iv(彈跳圖)碰到文字頂部時觸發監聽——這個時機正好是圖案向上彈到頂點的時刻,其間讓文字持續下凹再恢復。

 //用於播放文字下沉和上浮動畫傳入的數值必須是 圖片下沉和上升的一次時間 public void initAnimation(int duration){ //這裡為什maxElasticFactor/4 好看...另一個同理 這個數值大家自行調整 ValueAnimator animator = ValueAnimator.ofFloat(maxElasticFactor/4, (float) (maxElasticFactor / 1.5),0); animator.setDuration(duration/2); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { calc();//重新畫路徑 nowElasticFactor= (float) animation.getAnimatedValue(); postInvalidate(); } }); animator.start(); }

再配一個重新計算並繪製路徑的方法:

 public void calc(){ //重置路徑 path.reset(); //由於畫文字是由基准線開始 path.moveTo(iv.getX()-textWidth/2+iv.getWidth()/2, textHeight+iv.getHeight()+downHeight*iv.getHeight()); //畫二次貝塞爾曲線 path.rQuadTo(textWidth / 2, nowElasticFactor, textWidth, 0); }

至此,我們來看看完整源碼:

 package com.example.administrator.myapplication; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.util.AttributeSet; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.animation.AccelerateInterpolator; import android.view.animation.Animation; import android.view.animation.DecelerateInterpolator; import android.view.animation.TranslateAnimation; import android.widget.FrameLayout; import android.widget.ImageView; public class My extends FrameLayout { //畫筆 private Paint paint; //路徑 private Path path; //要輸入的文本 private String printText = "正在加載"; //文本寬 private float textWidth; //文本高 private float textHeight; //測量文字寬高的時候使用的矩形 private Rect rect; //最大彈力系數 private float elastic = 1.5f; //最大彈力 private float maxElasticFactor; //當前彈力 private float nowElasticFactor; //用於記錄當前圖片使用數組中的哪張 int indexImgFlag = 0; //下沉圖片 int allImgDown [] = {R.mipmap.p2,R.mipmap.p4,R.mipmap.p6,R.mipmap.p8}; //動畫效果一次下沉或上彈的時間 animationDuration*2=一次完整動畫時間 int animationDuration = 1000; //彈起來的圖片 ImageView iv; //圖片下沉高度(即從最高點到最低點的距離) int downHeight = 2; private Animation translateDown; private Animation translateUp; private ObjectAnimator rotation; public My(Context context) { super(context); } public My(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); canvas.drawTextOnPath(printText, path, 0, 0, paint); } //用於播放文字下沉和上浮動畫傳入的數值必須是 圖片下沉和上升的一次時間 public void initAnimation(int duration){ //這裡為什maxElasticFactor/4為什麼 ValueAnimator animator = ValueAnimator.ofFloat(maxElasticFactor/4, (float) (maxElasticFactor / 1.5),0); animator.setDuration(duration/2); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { calc(); nowElasticFactor= (float) animation.getAnimatedValue(); postInvalidate(); } }); animator.start(); } public void calc(){ //重置路徑 path.reset(); //由於畫文字是由基准線開始 path.moveTo(iv.getX()-textWidth/2+iv.getWidth()/2, textHeight+iv.getHeight()+downHeight*iv.getHeight()); //畫二次貝塞爾曲線 path.rQuadTo(textWidth / 2, nowElasticFactor, textWidth, 0); } //初始化彈跳動畫 public void MyAnmation(){ //下沉效果動畫 translateDown = new TranslateAnimation( Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0, Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,downHeight); translateDown.setDuration(animationDuration); //設置一個插值器 動畫將會播放越來越快 模擬重力 translateDown.setInterpolator(new AccelerateInterpolator()); //上彈動畫 translateUp = new TranslateAnimation( Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0, Animation.RELATIVE_TO_SELF,downHeight,Animation.RELATIVE_TO_SELF,0 ); translateUp.setDuration(animationDuration); ////設置一個插值器 動畫將會播放越來越慢 模擬反重力 translateUp.setInterpolator(new DecelerateInterpolator()); //當下沉動畫完成時播放啟動上彈 translateDown.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { iv.setImageResource(allImgDown[indexImgFlag]); rotation = ObjectAnimator.ofFloat(iv, "rotation", 180f, 360f); rotation.setDuration(1000); rotation.start(); } @Override public void onAnimationEnd(Animation animation) { iv.startAnimation(translateUp); initAnimation(animationDuration); } @Override public void onAnimationRepeat(Animation animation) { } }); //當上移動畫完成時 播放下移動畫 translateUp.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { indexImgFlag = 1+indexImgFlag>=allImgDown.length?0:1+indexImgFlag; iv.setImageResource(allImgDown[indexImgFlag]); rotation = ObjectAnimator.ofFloat(iv, "rotation", 0.0f, 180f); rotation.setDuration(1000); rotation.start(); } @Override public void onAnimationEnd(Animation animation) { //遞歸 iv.startAnimation(translateDown); } @Override public void onAnimationRepeat(Animation animation) { } }); } boolean flagMeure; @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); init(); } private void init() { //初始化彈跳圖片 控件 iv = new ImageView(getContext()); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); iv.setLayoutParams(params); iv.setImageResource(allImgDown[0]); this.addView(iv); //畫筆的初始化 paint = new Paint(); paint.setStrokeWidth(1); paint.setColor(Color.CYAN); paint.setStyle(Paint.Style.FILL); paint.setTextSize(50); paint.setAntiAlias(true); //矩形 Rect rect = new Rect(); //將文字畫入矩形目的是為了測量高度 paint.getTextBounds(printText, 0, printText.length(), rect); //文本寬度 textWidth = paint.measureText(printText); //獲得文字高度 textHeight = rect.bottom - rect.top; //初始化路徑 path = new Path(); iv.setX(getWidth()/2); iv.measure(0,0); iv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (!flagMeure) { flagMeure =true; //由於畫文字是由基准線開始 path.moveTo(iv.getX()-textWidth/2+iv.getWidth()/2, textHeight+iv.getHeight()+downHeight*iv.getHeight()); //計算最大彈力 maxElasticFactor = (float) (textHeight / elastic); //初始化貝塞爾曲線 path.rQuadTo(textWidth / 2, 0, textWidth, 0); //初始化上彈和下沉動畫 MyAnmation(); iv.startAnimation(translateDown); } } }); } }

完整源碼已附上,感興趣的朋友可以前往 GitHub 下載參考。

以上就是本文關於用自定義 View 實現阻尼效果加載動畫的分享,希望對你有所幫助。如有任何疑問,歡迎留言交流。

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