編輯:關於 Android 程式設計
先看效果

這個動畫看起來簡單,真要做得自然卻需要幾個知識點配合:
1. 属性動畫(ValueAnimator / AnimatorSet)
2. Path 與 Canvas 的繪製 API
3. 貝塞爾曲線
4. SurfaceView 的使用方式
5. 自定義 attr 屬性
6. 狀態模式與控制器分離的架構思路
7. 自由落體與拋物線運動的基本概念
整個動畫可以視為三段:小球把「繩子」壓下(下落)→ 繩子把小球彈起(上拋)→ 小球脫離繩子做自由飛行(拋物線)。三段各由一個 ValueAnimator 驅動,再用 AnimatorSet 串成序列,並以狀態變量標記當前處於哪一段,onDraw 依狀態決定怎麼畫。
public class DancingView extends SurfaceView implements SurfaceHolder.Callback {
public static final int STATE_DOWN = 1; // 向下
public static final int STATE_UP = 2; // 向上
public static final int DEFAULT_POINT_RADIUS = 10;
public static final int DEFAULT_BALL_RADIUS = 13;
public static final int DEFAULT_LINE_WIDTH = 200;
public static final int DEFAULT_LINE_HEIGHT = 2;
public static final int DEFAULT_LINE_COLOR = Color.parseColor("#FF9800");
public static final int DEFAULT_POINT_COLOR = Color.parseColor("#9C27B0");
public static final int DEFAULT_BALL_COLOR = Color.parseColor("#FF4081");
public static final int DEFAULT_DOWN_DURATION = 600; // ms
public static final int DEFAULT_UP_DURATION = 600; // ms
public static final int DEFAULT_FREEDOWN_DURATION = 1000; // ms
public static final int MAX_OFFSET_Y = 50; // 繩子最大下壓量
public int PONIT_RADIUS = DEFAULT_POINT_RADIUS;
public int BALL_RADIUS = DEFAULT_BALL_RADIUS;
private Paint mPaint;
private Path mPath;
private int mLineColor, mPonitColor, mBallColor;
private int mLineWidth, mLineHeight;
private float mDownDistance, mUpDistance, freeBallDistance;
private ValueAnimator mDownController; // 下壓
private ValueAnimator mUpController; // 上彈
private ValueAnimator mFreeDownController; // 自由飛行
private AnimatorSet animatorSet;
private int state;
private boolean ismUpControllerDied = false;
private boolean isAnimationShowing = false;
private boolean isBounced = false;
private boolean isBallFreeUp = false;
public DancingView(Context context) { super(context); init(context, null); }
public DancingView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); }
public DancingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
initAttributes(context, attrs);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(mLineHeight);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPath = new Path();
getHolder().addCallback(this);
initController();
}
/** 解析自定義屬性 */
private void initAttributes(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DancingView);
mLineColor = a.getColor(R.styleable.DancingView_lineColor, DEFAULT_LINE_COLOR);
mLineWidth = a.getDimensionPixelOffset(R.styleable.DancingView_lineWidth, DEFAULT_LINE_WIDTH);
mLineHeight = a.getDimensionPixelOffset(R.styleable.DancingView_lineHeight, DEFAULT_LINE_HEIGHT);
mPonitColor = a.getColor(R.styleable.DancingView_pointColor, DEFAULT_POINT_COLOR);
mBallColor = a.getColor(R.styleable.DancingView_ballColor, DEFAULT_BALL_COLOR);
a.recycle();
}
private void initController() {
// 第一段:下壓,減速插值器模擬重物下墜
mDownController = ValueAnimator.ofFloat(0, 1);
mDownController.setDuration(DEFAULT_DOWN_DURATION);
mDownController.setInterpolator(new DecelerateInterpolator());
mDownController.addUpdateListener(a ->
mDownDistance = MAX_OFFSET_Y * (float) a.getAnimatedValue());
mDownController.addListener(new SimpleAnimatorListener() {
@Override public void onAnimationStart(Animator animation) { state = STATE_DOWN; }
});
// 第二段:上彈,自定義阻尼振盪插值器
mUpController = ValueAnimator.ofFloat(0, 1);
mUpController.setDuration(DEFAULT_UP_DURATION);
mUpController.setInterpolator(new DancingInterpolator());
mUpController.addUpdateListener(a -> {
mUpDistance = MAX_OFFSET_Y * (float) a.getAnimatedValue();
if (mUpDistance >= MAX_OFFSET_Y) {
isBounced = true;
if (!mFreeDownController.isRunning()
&& !mFreeDownController.isStarted()
&& !isBallFreeUp) {
mFreeDownController.start();
}
}
});
mUpController.addListener(new SimpleAnimatorListener() {
@Override public void onAnimationStart(Animator animation) { state = STATE_UP; }
@Override public void onAnimationEnd(Animator animation) { ismUpControllerDied = true; }
});
// 第三段:脫離繩子後的拋物線飛行
mFreeDownController = ValueAnimator.ofFloat(0, 8f);
mFreeDownController.setDuration(DEFAULT_FREEDOWN_DURATION);
mFreeDownController.setInterpolator(new DecelerateInterpolator());
mFreeDownController.addUpdateListener(a -> {
// 該公式同時描述上升減速與下降加速
float t = (float) a.getAnimatedValue();
freeBallDistance = 40 * t - 5 * t * t;
if (ismUpControllerDied) postInvalidate();
});
mFreeDownController.addListener(new SimpleAnimatorListener() {
@Override public void onAnimationStart(Animator animation) { isBallFreeUp = true; }
@Override public void onAnimationEnd(Animator animation) {
isAnimationShowing = false;
startAnimations(); // 循環播放
}
});
animatorSet = new AnimatorSet();
animatorSet.play(mDownController).before(mUpController);
animatorSet.addListener(new SimpleAnimatorListener() {
@Override public void onAnimationStart(Animator animation) { isAnimationShowing = true; }
});
}
/** 對外暴露的啟動入口 */
public void startAnimations() {
if (isAnimationShowing) return;
if (animatorSet.isRunning()) {
animatorSet.end();
animatorSet.cancel();
}
isBounced = false;
isBallFreeUp = false;
ismUpControllerDied = false;
animatorSet.start();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setColor(mLineColor);
mPath.reset();
mPath.moveTo(getWidth() / 2 - mLineWidth / 2, getHeight() / 2);
if (state == STATE_DOWN) {
// 繩子:左右各一段二階貝塞爾曲線
mPath.quadTo((float) (getWidth() / 2 - mLineWidth / 2 + mLineWidth * 0.375),
getHeight() / 2 + mDownDistance,
getWidth() / 2, getHeight() / 2 + mDownDistance);
mPath.quadTo((float) (getWidth() / 2 + mLineWidth / 2 - mLineWidth * 0.375),
getHeight() / 2 + mDownDistance,
getWidth() / 2 + mLineWidth / 2, getHeight() / 2);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawPath(mPath, mPaint);
// 小球
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(mBallColor);
canvas.drawCircle(getWidth() / 2,
getHeight() / 2 + mDownDistance - BALL_RADIUS, BALL_RADIUS, mPaint);
} else if (state == STATE_UP) {
mPath.quadTo((float) (getWidth() / 2 - mLineWidth / 2 + mLineWidth * 0.375),
getHeight() / 2 + 50 - mUpDistance,
getWidth() / 2, getHeight() / 2 + (50 - mUpDistance));
mPath.quadTo((float) (getWidth() / 2 + mLineWidth / 2 - mLineWidth * 0.375),
getHeight() / 2 + 50 - mUpDistance,
getWidth() / 2 + mLineWidth / 2, getHeight() / 2);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawPath(mPath, mPaint);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(mBallColor);
if (!isBounced) {
// 仍在繩子上被拋起
canvas.drawCircle(getWidth() / 2,
getHeight() / 2 + (MAX_OFFSET_Y - mUpDistance) - BALL_RADIUS,
BALL_RADIUS, mPaint);
} else {
// 已脫離,走拋物線
canvas.drawCircle(getWidth() / 2,
getHeight() / 2 - freeBallDistance - BALL_RADIUS,
BALL_RADIUS, mPaint);
}
}
// 繩子两端的固定支點
mPaint.setColor(mPonitColor);
mPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(getWidth() / 2 - mLineWidth / 2, getHeight() / 2, PONIT_RADIUS, mPaint);
canvas.drawCircle(getWidth() / 2 + mLineWidth / 2, getHeight() / 2, PONIT_RADIUS, mPaint);
}
@Override public void surfaceCreated(SurfaceHolder holder) {
Canvas canvas = holder.lockCanvas();
draw(canvas);
holder.unlockCanvasAndPost(canvas);
}
@Override public void surfaceChanged(SurfaceHolder holder, int f, int w, int h) { }
@Override public void surfaceDestroyed(SurfaceHolder holder) { }
}
彈起那一段是整個動畫的靈魂。線性插值看起來像機器,配上帶阻尼的振盪函數才會有彈性:
public class DancingInterpolator implements Interpolator {
@Override
public float getInterpolation(float input) {
return (float) (1 - Math.exp(-3 * input) * Math.cos(10 * input));
}
}
exp(-3t) 提供逐漸衰減的振幅,cos(10t) 提供反覆振盪,兩者相乘再加上 1,就得到一條會來回幾次最後收斂到 1 的曲線。
<declare-styleable name="DancingView">
<attr name="lineWidth" format="dimension" />
<attr name="lineHeight" format="dimension" />
<attr name="pointColor" format="reference|color" />
<attr name="lineColor" format="reference|color" />
<attr name="ballColor" format="reference|color" />
</declare-styleable>
顏色、線寬、間距這些參數都開放成自定義屬性,實際專案裡可依設計稿自行調整,不必改原始碼。
這個元件的價值在於示範了「狀態機 + 多控制器」的動畫組織方式:三段運動各自獨立計時,靠 state 與幾個 boolean 標誌決定畫面,避免把物理計算全部塞進 onDraw。貝塞爾曲線負責繩子的柔軟感,自定義插值器負責彈性,兩者搭配就足以撐起一個觀感不錯的載入動畫。
用 Cordova 解決 HTML5 打包成 WebView 應用時的兼容性難題
一、Android 4.0 WebView 分析 Android 4.0 時代,WebView 的實現分布在 framework 與 WebKit 兩層:framewo
Android Loading 界面:以 Shader 實現動態圖片顯示
先看效果圖(方框由左至右依序顯示): 圖片資源: 原理介紹: 第一步:把三張圖片按位置擺放妥當。此時圖片資源會全部顯示,目的是先確保位置的正確性。 第二步:撰寫 sh
Android 學習之路:數據的存儲與使用(一)
今天是 Android 學習的第四天,上午簡單學習了數據的存儲與使用,這裡把上午的心得整理一下。 數據存儲主要分為四大類: * 檔案 * SharedPreference
仿微信的圖片拍攝與選擇界面實現
插件運行後的畫面如下: 下圖按照片來源進行篩選(分別來自QQ、微信和相機): 點擊某個文件夾後,可以查看該文件夾下的所有圖片: 圖片選擇界面: 選中後會