編輯:關於 Android 程式設計
之前在網路上看到一個 iOS 元件 PendulumView,做出了鐘擺擺動的動畫效果。由於原生進度條的外觀實在算不上好看,於是我思考能否用自定義 View 把這種效果做出來,之後也能用在載入頁面的進度提示上。
先上成果圖(底部黑邊是錄製時不小心入鏡的,可以忽略):

在專案的 res/values 目錄下新增 attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="PendulumView">
</declare-styleable>
</resources>
declare-styleable 的 name 用於在程式碼中引用這份屬性檔,慣例上直接寫自定義 View 的類名,最為直觀。使用 styleable 的好處是系統會自動幫我們產生 int[] 陣列與各項下標常量,例如後續用到的 R.styleable.PendulumView_globeNum,大幅簡化開發工作。
這裡定義的四個屬性分別是:globeNum(小球數量)、globeColor(小球顏色)、globeRadius(小球半徑)、swingRadius(擺動半徑)。
在自定義 View 的建構子中透過 TypedArray 取值:
public PendulumView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
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);
}
雖然也可以透過 AttributeSet 取值,但若屬性是引用型別,取到的只是資源 ID,還得再解析一次才能拿到真正的值;TypedArray 直接替我們完成了這件事。
@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 時採用外部指定值;其他情況(多為 wrap_content)則用自算結果
setMeasuredDimension((widthMode == MeasureSpec.EXACTLY) ? widthSize : width,
(heightMode == MeasureSpec.EXACTLY) ? heightSize : height);
}
這兩行計算主要處理 AT_MOST 模式,也就是自定義 View 的寬高設為 wrap_content 時,依小球數量、半徑與擺動半徑推算實際尺寸:
int height = mGlobeRadius + mSwingRadius; int width = mSwingRadius + mGlobeRadius * 2 * (mGlobeNum - 1) + mSwingRadius;
以 5 顆小球為例,View 的範圍就是下圖的紅色矩形區域:

@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);
}
onDraw 是自定義 View 的關鍵所在。程式先畫出中間那些固定不動的小球,再判斷左右兩顆的座標:首次繪製時座標為空,於是初始化並啟動動畫;之後每次重繪都依 mLeftPoint、mRightPoint 的 x、y 值畫出這兩顆球。這兩個物件都是 android.graphics.Point,單純用來存放座標資訊。
public void startPendulumAnimation() {
final ValueAnimator anim = ValueAnimator.ofObject(new TypeEvaluator() {
@Override
public Object evaluate(float fraction, Object startValue, Object endValue) {
// fraction 代表動畫完成度(0~1),據此推算目前的角度與位移
double angle = Math.toRadians(90 * fraction);
int x = (int) ((mSwingRadius - mGlobeRadius) * Math.sin(angle));
int y = (int) ((mSwingRadius - mGlobeRadius) * Math.cos(angle));
return new Point(x, y);
}
}, new Point(), new Point());
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
Point point = (Point) animation.getAnimatedValue();
float fraction = anim.getAnimatedFraction();
// fraction 由遞減轉為遞增,代表小球即將上拋,此時切換運動的小球
if (lastSlope && fraction > mLastFraction) {
isNext = !isNext;
}
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;
mLeftPoint.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();
}
使用 ValueAnimator.ofObject 是為了能直接操作 Point 物件,語意更貼近「座標在動」這件事。同時透過自定義的 TypeEvaluator 取得了 fraction——一個從 0 到 1 變化的比率。因此後兩個參數 startValue、endValue(此處都是 new Point())其實沒有實際意義,寫上純粹是為了便於理解;同樣的效果也可以直接用 ValueAnimator.ofFloat(0f, 1f) 取得。
double angle = Math.toRadians(90 * fraction); int x = (int) ((mSwingRadius - mGlobeRadius) * Math.sin(angle)); int y = (int) ((mSwingRadius - mGlobeRadius) * Math.cos(angle));
透過 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)。可見兩側小球的縱座標完全一致,只有橫座標不同。
float fraction = anim.getAnimatedFraction();
// 判斷 fraction 是否由遞減轉為遞增,即小球即將上拋
if (lastSlope && fraction > mLastFraction) {
isNext = !isNext;
}
// 記錄上一次 fraction 是否在不斷遞減
lastSlope = fraction < mLastFraction;
mLastFraction = fraction;
動畫設為循環播放且模式為 REVERSE,因此一個週期就是「上拋 + 落下」的過程,fraction 會由 0 增到 1、再由 1 減回 0。新一輪週期的起點,正是小球即將被拋起的時刻——此時切換運動主體,就能形成「左球落下後右球上拋、右球落下後左球上拋」的連續效果。
要捕捉這個瞬間並不難:小球上拋時 fraction 持續增大,落下時持續減小,因此「即將拋起」就等同於 fraction 從遞減翻轉為遞增的那一刻。程式記錄上一次是否處於遞減狀態,再比對這次是否轉為遞增,兩個條件同時成立便切換。
anim.setDuration(200); anim.setInterpolator(new DecelerateInterpolator()); anim.start();
duration 設為 200 毫秒,想調整擺動快慢只要改這個值。補間器方面,小球上拋是逐漸減速、落下是逐漸加速,因此使用 DecelerateInterpolator 來模擬減速,在 REVERSE 播放時自然呈現相反的加速效果。
啟動動畫,鐘擺風格的進度條自定義 View 就完成了,快跑起來看看實際效果吧。若內容有任何疏漏之處,還請不吝指正。
Android Bound Service(一):以 Extending Binder 實作進程內綁定
前言 重新把 Bound Service 學一遍,是因為當年實在沒好好學。那時候總覺得「能動、能交差就好」,這種心態嚴重拖慢了技術成長,這個部落格裡有不少都是那段時期的複
Android 官方文件導讀:Location and Sensors APIs(中)
本文接續介紹 Android 裝置中的各類感測器(Sensor),包含感測器概述、分類、框架,以及如何在程式中監聽感測器事件。感測器概述(Sensors Overview
Android 程式設計:實作圖片 3D 旋轉效果
本文分享一個在 Android 中實作圖片 3D 旋轉效果的實例,供大家參考。 接下來的示例要實作的是圖片的 3D 旋轉效果。 要做 3D 效果一般會想到 OpenGL,
Android 狀態欄微技巧:一次真正搞懂沉浸式模式
之前有讀者留言希望我寫一篇關於沉浸式狀態欄的文章,正好我也有這個打算,本篇就來一次把這個主題講清楚。 說到「沉浸式狀態欄」這個名字其實頗讓人無奈。Android 官方從未