編輯:關於 Android 程式設計
音樂播放器裡那張緩緩轉動的黑色唱片,幾乎已經成為「正在播放」的視覺符號。想在自己的 App 裡做出同樣的效果,其實不需要動畫框架,只要一個自定義 View 加上 Matrix 與 Handler 就能搞定。下面把整個實作過程拆成四個步驟,如果你只想要一張靜態的圓形頭像,第三步的旋轉邏輯可以直接刪掉。
先看最終效果:

onMeasure 中完成 View 的測量,決定自身的寬高。onDraw 裡把它裁切並繪製成正圓。Handler 送出 Runnable,週期性重繪以驅動旋轉。// view 的寬和高 int mHeight = 0; int mWidth = 0; // 圓形圖片 Bitmap bitmap = null; // 圓形圖片的真實半徑 int radius = 0; // 旋轉動畫的矩陣 Matrix matrix = new Matrix(); // 旋轉動畫的角度 int degrees = 0;
這裡的關鍵是正確處理 MeasureSpec 的三種模式:當父容器明確指定尺寸時採用 EXACTLY;當尺寸為 AT_MOST 時,則以圖片尺寸加上 padding 作為期望值,但不能超出父容器給定的上限。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = measuredWidth(widthMeasureSpec);
mHeight = measuredHeight(heightMeasureSpec);
setMeasuredDimension(mWidth, mHeight);
}
private int measuredWidth(int widthMeasureSpec) {
int mode = MeasureSpec.getMode(widthMeasureSpec);
int size = MeasureSpec.getSize(widthMeasureSpec);
if (mode == MeasureSpec.EXACTLY) {
mWidth = size;
} else {
int value = getPaddingLeft() + getPaddingRight() + bitmap.getWidth();
if (mode == MeasureSpec.AT_MOST) {
mWidth = Math.min(value, size);
}
}
return mWidth;
}
private int measuredHeight(int heightMeasureSpec) {
int mode = MeasureSpec.getMode(heightMeasureSpec);
int size = MeasureSpec.getSize(heightMeasureSpec);
if (mode == MeasureSpec.EXACTLY) {
mHeight = size;
} else {
int value = getPaddingTop() + getPaddingBottom() + bitmap.getHeight();
if (mode == MeasureSpec.AT_MOST) {
mHeight = Math.min(value, size);
}
}
return mHeight;
}
先從資源中解碼出 Bitmap:
// 取得 res 的圖片資源 bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
接著在 onDraw 中先套用旋轉矩陣,再繪製圓形圖片,最後把矩陣還原,避免影響下一次繪製。裁切圓形的手法是經典的 PorterDuff.Mode.SRC_IN 合成:先畫一個圓,再用該模式把圖片貼上去,只保留交集部分。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.concat(matrix);
// 真實的半徑取寬高最小值
radius = Math.min(mWidth, mHeight);
// 若原圖過大,先縮放
bitmap = Bitmap.createScaledBitmap(bitmap, radius, radius, false);
// 繪製圓形圖片
canvas.drawBitmap(createCircleImage(bitmap, radius), 0, 0, null);
matrix.reset();
}
private Bitmap createCircleImage(Bitmap source, int radius) {
Paint paint = new Paint();
paint.setAntiAlias(true);
Bitmap target = Bitmap.createBitmap(radius, radius, Bitmap.Config.ARGB_8888);
// 建立同尺寸的畫布
Canvas canvas = new Canvas(target);
// 先畫圓
canvas.drawCircle(radius / 2, radius / 2, radius / 2, paint);
// 以 SRC_IN 模式只保留交集處
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, 0, 0, paint);
return target;
}
在 initView() 中啟動任務:
// 開始旋轉 mHandler.post(runnable);
每次執行時把角度加一、以圓心為軸心旋轉,然後 invalidate() 觸發重繪,並以 50 毫秒的間隔延遲投遞下一次任務,如此便形成連續動畫。
//----------- 旋轉動畫 -----------
Handler mHandler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
matrix.postRotate(degrees++, radius / 2, radius / 2);
invalidate();
mHandler.postDelayed(runnable, 50);
}
};
<com.handsome.cycle.mycycleview
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</com.handsome.cycle.mycycleview>
public class MyCycleView extends View {
int mHeight = 0;
int mWidth = 0;
Bitmap bitmap = null;
int radius = 0;
Matrix matrix = new Matrix();
int degrees = 0;
Handler mHandler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
matrix.postRotate(degrees++, radius / 2, radius / 2);
invalidate();
mHandler.postDelayed(runnable, 50);
}
};
public MyCycleView(Context context) {
super(context);
initView();
}
public MyCycleView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public MyCycleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
public void initView() {
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
mHandler.post(runnable);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = measuredWidth(widthMeasureSpec);
mHeight = measuredHeight(heightMeasureSpec);
setMeasuredDimension(mWidth, mHeight);
}
private int measuredWidth(int widthMeasureSpec) {
int mode = MeasureSpec.getMode(widthMeasureSpec);
int size = MeasureSpec.getSize(widthMeasureSpec);
if (mode == MeasureSpec.EXACTLY) {
mWidth = size;
} else {
int value = getPaddingLeft() + getPaddingRight() + bitmap.getWidth();
if (mode == MeasureSpec.AT_MOST) {
mWidth = Math.min(value, size);
}
}
return mWidth;
}
private int measuredHeight(int heightMeasureSpec) {
int mode = MeasureSpec.getMode(heightMeasureSpec);
int size = MeasureSpec.getSize(heightMeasureSpec);
if (mode == MeasureSpec.EXACTLY) {
mHeight = size;
} else {
int value = getPaddingTop() + getPaddingBottom() + bitmap.getHeight();
if (mode == MeasureSpec.AT_MOST) {
mHeight = Math.min(value, size);
}
}
return mHeight;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.concat(matrix);
radius = Math.min(mWidth, mHeight);
bitmap = Bitmap.createScaledBitmap(bitmap, radius, radius, false);
canvas.drawBitmap(createCircleImage(bitmap, radius), 0, 0, null);
matrix.reset();
}
private Bitmap createCircleImage(Bitmap source, int radius) {
Paint paint = new Paint();
paint.setAntiAlias(true);
Bitmap target = Bitmap.createBitmap(radius, radius, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(target);
canvas.drawCircle(radius / 2, radius / 2, radius / 2, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, 0, 0, paint);
return target;
}
}
這個自定義 View 的骨架很輕,實際專案裡還可以再補強幾處:例如把旋轉速度抽成自定義屬性、在 onDetachedFromWindow 中移除 Handler 回呼避免記憶體洩漏,以及用 invalidate() 之外改走硬體加速的顯示列表。若只是要做圓形頭像,把 Runnable 相關的程式碼拿掉即可,剩下的 createCircleImage 就是一個現成的圓角裁切工具。
Android Tab 實作:Fragment 與 FragmentManager 切換
使用 Fragment 與 FragmentManager 實作 Tab 切換,是常見且靈活的 Android 介面設計方式。透過上方標籤與下方內容區域的搭配,可以在同一
Android SwipeRefreshLayout 下拉刷新使用說明
SwipeRefreshLayout 簡介 SwipeRefreshLayout 是 Android 支援庫提供的下拉刷新控制元件,常出現在 Gmail 等應用中。它只能
用 OkHttp 處理 GET 與 POST 請求的實作筆記
HTTP 是當今 App 交換資料最主流的方式,用得好可以讓應用跑得更快、更省流量。OkHttp 就是為此而生的一個優秀 HTTP 客戶端(主頁:https://gith
從 StackTraceElement 看 Android 日誌庫設計
為什麼需要封裝 Log 開發時經常需要臨時加入大量日誌,修完問題後又要逐行刪除,既麻煩又容易遺漏。若能封裝日誌工具,不僅可以透過開關控制輸出,還能讓日誌自帶檔案名稱與行號