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

自定義View實作圓形旋轉唱片:手把手打造QQ音樂風格黑膠碟動畫

編輯:關於 Android 程式設計

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

先看最終效果:

整體思路

  1. 在 onMeasure 中完成 View 的測量,決定自身的寬高。
  2. 載入 res 中的圖片資源,在 onDraw 裡把它裁切並繪製成正圓。
  3. 用 Handler 送出 Runnable,週期性重繪以驅動旋轉。
  4. 在佈局檔中直接引用這個 View。

成員變量準備

// view 的寬和高
int mHeight = 0;
int mWidth = 0;
// 圓形圖片
Bitmap bitmap = null;
// 圓形圖片的真實半徑
int radius = 0;
// 旋轉動畫的矩陣
Matrix matrix = new Matrix();
// 旋轉動畫的角度
int degrees = 0;

步驟一:測量 View 的寬高

這裡的關鍵是正確處理 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;
}

步驟三:用 Handler 驅動旋轉

在 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 就是一個現成的圓角裁切工具。

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