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

自定義 View 實作:隨音量變化的圓形錄音按鈕

編輯:關於 Android 程式設計

所謂無圖無真相,先來看效果圖。我們要實現的,是中間那個錄音按鈕——其周邊會顯示一圈隨音量大小變化的波形。

設計思路

VolumCircleBar 繼承自 View,透過自定義繪製實現整個效果。核心思路是:以圓心為中心,將一圈劃分為若干個扇區(block),再根據當前音量百分比決定點亮多少個扇區,從而在圓周上呈現出隨音量起伏的波形。同時,圓心處繪製一個麥克風圖示。

核心程式碼

public class VolumCircleBar extends View {
    private double volumRate;          // 音量百分比
    private boolean isRecording;       // 錄音標志
    private Object lock = new Object();
    private Paint mPaint;
    private RectF arcRect;
    private Matrix matrix = new Matrix();

    private final int VOLUM_INDICATE_LENGTH = 5;              // 音量線長度
    private final int CIRCLE_INNER_DISTANCE_TO_OUTSIDE = 5;   // 內切圓距外圓的距離

    private int recordingColor;   // 錄音背景色
    private int stoppedColor;     // 停止背景色
    private Bitmap centerRes;     // 中間麥克風圖片
    private int totalBlockCount;  // 扇區數量
    private int spliteAngle;      // 扇區間隔角度
    private int circleWidth;      // 直徑

    public VolumCircleBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(
            attrs, R.styleable.VolumCircleBar, defStyle, 0);
        init(typedArray);
    }

    private void init(TypedArray typedArray) {
        for (int i = 0; i < typedArray.length(); i++) {
            int attr = typedArray.getIndex(i);
            switch (attr) {
                case R.styleable.VolumCircleBar_recordingColor:
                    recordingColor = typedArray.getColor(i, Color.GREEN); break;
                case R.styleable.VolumCircleBar_stoppedColor:
                    stoppedColor = typedArray.getColor(i, Color.GRAY); break;
                case R.styleable.VolumCircleBar_centerRes:
                    centerRes = BitmapFactory.decodeResource(getContext().getResources(),
                        typedArray.getResourceId(i, R.drawable.ic_launcher)); break;
                case R.styleable.VolumCircleBar_blockCount:
                    totalBlockCount = typedArray.getInt(i, 50); break;
                case R.styleable.VolumCircleBar_splitAngle:
                    spliteAngle = typedArray.getInt(i, 2); break;
            }
        }
        typedArray.recycle();
        mPaint = new Paint();
        if (spliteAngle * totalBlockCount > 360) {
            throw new IllegalArgumentException(
                "spliteAngle * blockCount 應小於 360。");
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        circleWidth = width > height ? width : height;
        if (arcRect == null) {
            arcRect = new RectF(CIRCLE_INNER_DISTANCE_TO_OUTSIDE,
                CIRCLE_INNER_DISTANCE_TO_OUTSIDE,
                circleWidth - CIRCLE_INNER_DISTANCE_TO_OUTSIDE,
                circleWidth - CIRCLE_INNER_DISTANCE_TO_OUTSIDE);
            initBitmapMatrix();
        }
        setMeasuredDimension(circleWidth, circleWidth);
    }

    // 設定音量百分比
    public void updateVolumRate(double rate) {
        synchronized (lock) {
            this.volumRate = rate;
            if (Thread.currentThread() != uiThread) postInvalidate();
            else invalidate();
        }
    }

    // 開始、停止錄音
    public void toggleRecord() {
        synchronized (lock) {
            isRecording = !isRecording;
            if (Thread.currentThread() != uiThread) postInvalidate();
            else invalidate();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.TRANSPARENT);
        synchronized (lock) {
            if (isRecording) {
                // 1. 繪製綠色圓圈
                mPaint.setAntiAlias(true);
                mPaint.setColor(recordingColor);
                mPaint.setStyle(Paint.Style.FILL);
                canvas.drawCircle(circleWidth / 2f, circleWidth / 2f, circleWidth / 2f, mPaint);

                // 2. 依音量百分比動態繪製波形
                float blockAngle = (360f - spliteAngle * totalBlockCount) / totalBlockCount;
                int drawBlockCount = (int) (totalBlockCount * volumRate);
                mPaint.setStrokeWidth(VOLUM_INDICATE_LENGTH);
                mPaint.setColor(stoppedColor);
                mPaint.setStyle(Paint.Style.STROKE);
                for (int i = 0; i < drawBlockCount; i++) {
                    canvas.drawArc(arcRect, i * (blockAngle + spliteAngle) - 90,
                        blockAngle, false, mPaint);
                }
            } else {
                // 錄音停止,繪製灰色圓圈
                mPaint.setColor(stoppedColor);
                mPaint.setStyle(Paint.Style.FILL);
                canvas.drawCircle(circleWidth / 2f, circleWidth / 2f, circleWidth / 2f, mPaint);
            }
        }
        // 繪製中間麥克風
        canvas.drawBitmap(centerRes, matrix, null);
    }
}

關鍵要點

整個自定義 View 的精髓在於幾點:透過自訂屬性(attrs)靈活配置顏色、扇區數量與間隔角度;在 onMeasure 中計算圓形尺寸並初始化繪製區域;利用 Matrix 對中間的麥克風圖示進行等比縮放與居中處理;而在 onDraw 中,先繪製底色圓圈,再依 volumRate 決定點亮的扇區數量,配合 drawArc 描繪出環形波形。

此外,updateVolumRate 與 toggleRecord 都透過 synchronized 保護共享狀態,並根據當前是否為 UI 線程,分別調用 invalidate 或 postInvalidate 觸發重繪,確保多執行緒下的繪製安全。將它接入錄音音量回呼,便能得到一個隨聲音起伏而動的動態圓形按鈕。

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