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

Android 自定義 View 實現鐘擺風格加載動畫

編輯:關於 Android 程式設計

之前在網上看到一個 iOS 的 PendulumView 組件,小球來回擺動的效果很討喜。原生進度條實在看不上眼,於是琢磨著用自定義 View 復刻一個,之後可以用在頁面加載的等待態。

按自定義 View 的標準流程走:定義屬性 → 讀取屬性 → 測量 → 繪製 → 動畫。

一、定義自定義屬性

在 res/values 下新建 attrs.xml:

 <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="PendulumView"> <attr name="globeNum" format="integer"/> <attr name="globeColor" format="color"/> <attr name="globeRadius" format="dimension"/> <attr name="swingRadius" format="dimension"/> </declare-styleable> </resources> 

declare-styleable 的 name 一般直接寫自定義 View 的類名,最直觀。四個屬性分別是小球數量、顏色、半徑與擺動半徑。

使用 styleable 的好處是系統會自動生成 R.styleable.PendulumView_globeNum 這類常量數組與下標,省掉大量手寫的 index 維護工作。

二、讀取屬性值

雖然 AttributeSet 也能取屬性,但遇到引用類型的資源值只會拿到 ID,還要自己再解析一次。TypedArray 直接把這層工作做完了:

 public PendulumView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //使用TypedArray讀取自定義的屬性值 TypedArray ta = context.getResources().obtainAttributes(attrs, R.styleable.PendulumView); int count = ta.getIndexCount(); for (int i = 0; i < count; i++) { int attr = ta.getIndex(i); switch (attr) { case R.styleable.PendulumView_globeNum: mGlobeNum = ta.getInt(attr, 5); break; case R.styleable.PendulumView_globeRadius: mGlobeRadius = ta.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 16, getResources().getDisplayMetrics())); break; case R.styleable.PendulumView_globeColor: mGlobeColor = ta.getColor(attr, Color.BLUE); break; case R.styleable.PendulumView_swingRadius: mSwingRadius = ta.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 16, getResources().getDisplayMetrics())); break; } } ta.recycle(); //避免下次讀取時出現問題 mPaint = new Paint(); mPaint.setColor(mGlobeColor); } 

記得調用 recycle(),這在很多自定義 View 教程裡都被省略,但實際上是必要的。

三、重寫 onMeasure

 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); //高度為小球半徑+擺動半徑 int height = mGlobeRadius + mSwingRadius; //寬度為2*擺動半徑+(小球數量-1)*小球直徑 int width = mSwingRadius + mGlobeRadius * 2 * (mGlobeNum - 1) + mSwingRadius; //如果測量模式為EXACTLY,則直接使用推薦值,如不為EXACTLY(一般處理wrap_content情況),使用自己計算的寬高 setMeasuredDimension((widthMode == MeasureSpec.EXACTLY) ? widthSize : width, (heightMode == MeasureSpec.EXACTLY) ? heightSize : height); }

這段處理的是 wrap_content 場景:外部沒給明確尺寸時,就依據小球數量、半徑和擺動半徑自行推算。以 5 個小球為例,控件總寬 = 兩側各一個擺動半徑 + 中間 4 個小球的直徑。

四、重寫 onDraw

 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //繪制除左右兩個小球外的其他小球 for (int i = 0; i < mGlobeNum - 2; i++) { canvas.drawCircle(mSwingRadius + (i + 1) * 2 * mGlobeRadius, mSwingRadius, mGlobeRadius, mPaint); } if (mLeftPoint == null || mRightPoint == null) { //初始化最左右兩小球坐標 mLeftPoint = new Point(mSwingRadius, mSwingRadius); mRightPoint = new Point(mSwingRadius + mGlobeRadius * 2 * (mGlobeNum - 1), mSwingRadius); //開啟擺動動畫 startPendulumAnimation(); } //繪制左右兩小球 canvas.drawCircle(mLeftPoint.x, mLeftPoint.y, mGlobeRadius, mPaint); canvas.drawCircle(mRightPoint.x, mRightPoint.y, mGlobeRadius, mPaint); } 

中間那些小球位置固定,直接畫;只有最左和最右兩個小球需要運動,所以單獨維護它們的坐標對象(android.graphics.Point),並在首次繪製時初始化坐標、順帶啟動動畫。

五、屬性動畫驅動擺動

 public void startPendulumAnimation() { //使用屬性動畫 final ValueAnimator anim = ValueAnimator.ofObject(new TypeEvaluator() { @Override public Object evaluate(float fraction, Object startValue, Object endValue) { //參數fraction用於表示動畫的完成度,我們根據它來計算當前的動畫值 double angle = Math.toRadians(90 * fraction); int x = (int) ((mSwingRadius - mGlobeRadius) * Math.sin(angle)); int y = (int) ((mSwingRadius - mGlobeRadius) * Math.cos(angle)); Point point = new Point(x, y); return point; } }, new Point(), new Point()); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { Point point = (Point) animation.getAnimatedValue(); //獲得當前的fraction值 float fraction = anim.getAnimatedFraction(); //判斷是否是fraction先減小後增大,即是否處於即將向上擺動狀態 //在每次即將向上擺動時切換小球 if (lastSlope && fraction > mLastFraction) { isNext = !isNext; } //通過不斷改動左右小球的x,y坐標值實現動畫效果 if (isNext) { //當左邊小球擺動時,右邊小球置於初始位置 mRightPoint.x = mSwingRadius + mGlobeRadius * 2 * (mGlobeNum - 1); mRightPoint.y = mSwingRadius; mLeftPoint.x = mSwingRadius - point.x; mLeftPoint.y = mGlobeRadius + point.y; } else { //當右邊小球擺動時,左邊小球置於初始位置 mLeftPoint.x = mSwingRadius; mRightPoint.y = mSwingRadius; mRightPoint.x = mSwingRadius + (mGlobeNum - 1) * mGlobeRadius * 2 + point.x; mRightPoint.y = mGlobeRadius + point.y; } invalidate(); lastSlope = fraction < mLastFraction; mLastFraction = fraction; } }); //設置永久循環播放 anim.setRepeatCount(ValueAnimator.INFINITE); //設置循環模式為倒序播放 anim.setRepeatMode(ValueAnimator.REVERSE); anim.setDuration(200); //設置補間器,控制動畫的變化速率 anim.setInterpolator(new DecelerateInterpolator()); anim.start(); } 

為什麼用 ofObject 而不是 ofFloat

ValueAnimator.ofObject 搭配自定義 TypeEvaluator,可以直接把計算結果封裝成 Point 對象返回,語義更清晰。實際上這個 Evaluator 並沒用到傳入的 startValue / endValue(寫 new Point() 只是為了便於理解),因為真正驅動計算的是 fraction——一個從 0 到 1 遞變的完成度。若嫌麻煩,直接用 ofFloat(0f, 1f) 拿這個小數也完全可行。

擺動軌道的數學關係

把 fraction 映射到 0–90 度的角度,小球圓心走的其實是一段圓弧,半徑為 mSwingRadius - mGlobeRadius(即下圖綠色線段)。因此相對偏移量為:

x = (mSwingRadius - mGlobeRadius) × sin(angle),y = (mSwingRadius - mGlobeRadius) × cos(angle)

換算成實際圓心坐標,左球是 (mSwingRadius − x, mGlobeRadius + y),右球是 (mSwingRadius + (mGlobeNum−1) × mGlobeRadius × 2 + x, mGlobeRadius + y)。可見兩球縱坐標始終相同,只有橫坐標方向相異。

如何抓住「換球」的時機

動畫設為無限循環且倒序播放,所以一個週期是「拋起 + 落下」的完整過程,fraction 由 0 增到 1 再降回 0。新一輪應該在小球即將被拋起的瞬間開始,也就是 fraction 從「持續減小」轉為「持續增大」的那一刻。

 float fraction = anim.getAnimatedFraction(); //判斷是否是fraction先減小後增大,即是否處於即將向上擺動狀態 //在每次即將向上擺動時切換小球 if (lastSlope && fraction > mLastFraction) { isNext = !isNext; } //記錄上一次fraction是否不斷減小 lastSlope = fraction < mLastFraction; //記錄上一次的fraction mLastFraction = fraction; 

只需保存上一幀的 fraction 及其變化趨勢,兩次判斷即可精確捕捉這個轉折點,然後用 isNext 標記該由左球還是右球運動。這種「用趨勢判斷代替硬編碼計時」的思路,比用定時器切換要優雅得多,也不會隨設備刷新率漂移。

速度與手感

 anim.setDuration(200); //設置補間器,控制動畫的變化速率 anim.setInterpolator(new DecelerateInterpolator()); anim.start();

duration 直接決定擺動快慢,可按設計稿調整。插值器選 DecelerateInterpolator 是為了模擬物理直覺:拋起過程逐漸減速,倒序播放時自然變為落下過程的逐漸加速。一個小小的加載動畫,物理感就出來了。

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