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

Android 自定義水波紋(Ripple)動畫 Layout 實戰

編輯:關於 Android 程式設計

話不多說,先來看看效果:

下面再分享幾個應用於真實場景的優秀開源項目,感興趣的同學可以體驗。

開源項目推薦

Hi 前輩搜索預覽

這張是《Hi 前輩》的搜索預覽圖,可在這裡下載體驗更多效果:

https://www.wandoujia.com/apps/com.superlity.hiqianbei

LSearchView

這是一個 MD 風格的搜索框,集成了 ripple 動畫與搜索時的 loading,接入簡單,需要的同學可以試試:https://github.com/onlynight/LSearchView

RippleEverywhere

女友的照片:

女友的照片:

這是一個水波紋動畫支持庫,目前僅支持 Android 4.0 以上版本:https://github.com/onlynight/RippleEverywhere

實現原理

本動畫基於屬性動畫實現。由於 Android 2.3 以下機型已非主流,因此只兼容 4.0 以上系統。若還不熟悉屬性動畫,可以先看看相關入門文章:https://www.jb51.net/article/82668.htm

在我看來,屬性動畫有點像一個「定時器」:所謂定時器,就是獨立於主線程之外的計時線程,每當到達設定時間就通知你;而屬性動畫不僅如此,它還能操作主線程的 UI 元素屬性,這說明其內部已經做好了線程同步。

核心原理

先看關鍵代碼:

 @Override protected void onDraw(Canvas canvas) { if (running) { // get canvas current state final int state = canvas.save(); // add circle to path to crate ripple animation // attention: you must reset the path first, // otherwise the animation will run wrong way. ripplePath.reset(); ripplePath.addCircle(centerX, centerY, radius, Path.Direction.CW); canvas.clipPath(ripplePath); // the {@link View#onDraw} method must be called before // {@link Canvas#restoreToCount}, or the change will not appear. super.onDraw(canvas); canvas.restoreToCount(state); return; } // in a normal condition, you should call the // super.onDraw the draw the normal situation. super.onDraw(canvas); } Canvas#save()和Canvas#restoreToCount()

這兩個方法用於保存與恢復繪制狀態:繪制前先保存上一狀態,繪制完成後再恢復,如此循環,直到 running 變為 false,中間的過程就是動畫本身。

Path#addCircle() 和 Canvas#clipPath():addCircle 用於在 path 上畫一個圓;clipPath 則對 path 進行剪切,只繪制 path 內的區域,其餘部分不繪制。

 radiusAnimator = ObjectAnimator.ofFloat(this, "animValue", 0, 1); /** * This method will be called by {@link this#radiusAnimator} * reflection calls. * * @param value animation current value */ public void setAnimValue(float value) { this.radius = value * maxRadius; System.out.println("radius = " + this.radius); invalidate(); }

這段是動效的關鍵:先準備一個隨時間推移而變化的值,每當該值變化時就刷新界面、觸發重繪。由於不能直接手動調用 onDraw,這裡借助系統提供的 invalidate 方法強制 View 重繪,進而回調 onDraw。

以上就是水波紋動畫的全部關鍵原理,下面給出一份完整源碼:

 import android.animation.Animator; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.graphics.Path; import android.util.AttributeSet; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.ImageView; /** * Created by lion on 2016/11/11. * <p> * RippleImageView use the {@link Path#addCircle} function * to draw the view when {@link RippleImageView#onDraw} called. * <p> * When you call {@link View#invalidate()} function,then the * {@link View#onDraw(Canvas)} will be called. In that way you * can use {@link Path#addCircle} to draw every frame, you will * see the ripple animation. */ public class RippleImageView extends ImageView { // view center x private int centerX = 0; // view center y private int centerY = 0; // ripple animation current radius private float radius = 0; // the max radius that ripple animation need private float maxRadius = 0; // record the ripple animation is running private boolean running = false; private ObjectAnimator radiusAnimator; private Path ripplePath; public RippleImageView(Context context) { super(context); init(); } public RippleImageView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public RippleImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @TargetApi(21) public RippleImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { ripplePath = new Path(); // initial the animator, when animValue change, // radiusAnimator will call {@link this#setAnimValue} method. radiusAnimator = ObjectAnimator.ofFloat(this, "animValue", 0, 1); radiusAnimator.setDuration(1000); radiusAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); radiusAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { running = true; } @Override public void onAnimationEnd(Animator animator) { running = false; } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); centerX = (right - left) / 2; centerY = (bottom - top) / 2; maxRadius = maxRadius(left, top, right, bottom); } /** * Calculate the max ripple animation radius. * * @param left view left * @param top view top * @param right view right * @param bottom view bottom * @return */ private float maxRadius(int left, int top, int right, int bottom) { return (float) Math.sqrt(Math.pow(right - left, 2) + Math.pow(bottom - top, 2) / 2); } /** * This method will be called by {@link this#radiusAnimator} * reflection calls. * * @param value animation current value */ public void setAnimValue(float value) { this.radius = value * maxRadius; System.out.println("radius = " + this.radius); invalidate(); } @Override protected void onDraw(Canvas canvas) { if (running) { // get canvas current state final int state = canvas.save(); // add circle to path to crate ripple animation // attention: you must reset the path first, // otherwise the animation will run wrong way. ripplePath.reset(); ripplePath.addCircle(centerX, centerY, radius, Path.Direction.CW); canvas.clipPath(ripplePath); // the {@link View#onDraw} method must be called before // {@link Canvas#restoreToCount}, or the change will not appear. super.onDraw(canvas); canvas.restoreToCount(state); return; } // in a normal condition, you should call the // super.onDraw the draw the normal situation. super.onDraw(canvas); } /** * call the {@link Animator#start()} function to start the animation. */ public void startAnimation() { if (radiusAnimator.isRunning()) { radiusAnimator.cancel(); } radiusAnimator.start(); } }

以上就是 Android 自定義水波紋動畫 Layout 的完整實現,希望對大家有所幫助。如有任何疑問,歡迎留言交流。

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