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

Android 自定義 View 實現音頻條形圖動畫

編輯:關於 Android 程式設計

這是一個模擬音頻輸出的條形圖。由於重點在自定義 View 的繪製邏輯,這裡不去真實讀取音頻振幅,而是用隨機數模擬數據變化。

第一步:畫出靜態的矩形序列

實現思路很直白:畫若干個豎向矩形,每個矩形之間留一點間距。關鍵是橫向坐標的遞推關係:

for (int i = 0; i < mRectCount; i++) {
    // drawRect 的四個參數分別是 left、top、right、bottom
    // 左右邊距左邊畫布邊界的距離,上下邊距上邊畫布邊界的距離
    canvas.drawRect(
            (float) (mRectWidth * i + offset),
            currentHeight,
            (float) (mRectWidth * (i + 1)),
            mRectHeight,
            mRectPaint);
}

注意這裡的 y 軸處理:top 傳入 currentHeight,bottom 固定為 mRectHeight。這意味著矩形是「底部對齊」的,高度變化時頂端上下浮動,視覺上就像音頻柱從底部生長——這正是我們想要的效果。

第二步:讓高度隨機變化

// 簡化處理,不真實監聽音頻輸入,用隨機數模擬
mRandom = Math.random();
currentHeight = (float) (mRectHeight * mRandom);

這樣靜態效果就有了,但每次重繪的形狀都是固定的。

第三步:驅動持續重繪

讓它動起來只需要在 onDraw() 末尾調用 invalidate()。但這裡有個陷阱:如果畫完立刻重繪,刷新頻率會高到超過螢幕同步,既浪費性能又可能出現撕裂。

正確做法是延遲重繪:

postInvalidateDelayed(300);

每 300 毫秒刷新一次,既能得到流暢的視覺效果,又不會給主線程造成壓力。這個間隔值應該做成可配置項,方便按實際體感調整。

第四步:加上漸變著色

純色矩形看起來比較「工程風」。用 LinearGradient 給畫筆掛一個著色器,視覺層次立刻不一樣:

@Override
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
    super.onSizeChanged(w, h, oldW, oldH);

    LinearGradient mLinearGradient;
    int mWidth;

    mWidth = getWidth();          // 畫布寬度
    mRectHeight = getHeight();    // 矩形最大高度

    // 單個矩形寬度,減去 offset 是預留給最後一個矩形的右間距
    mRectWidth = (mWidth - offset) / mRectCount;

    // 實例化線性漸變:從 (0,0) 到 (mRectWidth, mRectHeight)
    mLinearGradient = new LinearGradient(
            0, 0, mRectWidth, mRectHeight,
            topColor, downColor,
            Shader.TileMode.CLAMP);

    // 掛到畫筆上
    mRectPaint.setShader(mLinearGradient);
}

為什麼把這些計算放在 onSizeChanged() 而不是 onDraw()?因為寬高只在尺寸變化時才需要重算,放對地方能省下大量重複運算。onDraw() 會被高頻調用,裡面每一條語句都值得反覆審視。

完整代碼

package com.example.customaf;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;

import com.example.afanalog.R;

/**
 * 自定義的音頻模擬條形圖
 */
public class MyAF extends View {

    private int mRectCount;          // 矩形數量
    private Paint mRectPaint;        // 矩形畫筆
    private int topColor, downColor; // 漸變色的起止顏色
    private int mRectWidth, mRectHeight;
    private int offset;              // 矩形間距
    private int mSpeed;              // 重繪間隔(毫秒)

    public MyAF(Context context) {
        super(context);
    }

    public MyAF(Context context, AttributeSet attrs) {
        super(context, attrs);
        setPaint(context, attrs);
    }

    public MyAF(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setPaint(context, attrs);
    }

    private void setPaint(Context context, AttributeSet attrs) {
        // 把自定義屬性讀進 TypedArray
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyAF);

        mRectPaint = new Paint();

        // 漸變起始色,同時作為基礎色
        topColor = ta.getColor(R.styleable.MyAF_AFTopColor,
                ContextCompat.getColor(context, R.color.top_color));
        // 漸變結束色
        downColor = ta.getColor(R.styleable.MyAF_AFDownColor,
                ContextCompat.getColor(context, R.color.down_color));
        // 矩形數量
        mRectCount = ta.getInt(R.styleable.MyAF_AFCount, 10);
        // 重繪間隔
        mSpeed = ta.getInt(R.styleable.MyAF_AFSpeed, 300);
        // 矩形間距
        offset = ta.getInt(R.styleable.MyAF_AFOffset, 5);

        ta.recycle(); // 用完務必回收
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldW, int oldH) {
        super.onSizeChanged(w, h, oldW, oldH);
        int mWidth = getWidth();
        mRectHeight = getHeight();
        mRectWidth = (mWidth - offset) / mRectCount;

        LinearGradient mLinearGradient = new LinearGradient(
                0, 0, mRectWidth, mRectHeight,
                topColor, downColor,
                Shader.TileMode.CLAMP);
        mRectPaint.setShader(mLinearGradient);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        double mRandom;
        float currentHeight;

        for (int i = 0; i < mRectCount; i++) {
            // 用隨機數模擬音頻振幅
            mRandom = Math.random();
            currentHeight = (float) (mRectHeight * mRandom);

            canvas.drawRect(
                    (float) (mRectWidth * i + offset),
                    currentHeight,
                    (float) (mRectWidth * (i + 1)),
                    mRectHeight,
                    mRectPaint);
        }

        // 延遲重繪,控制刷新節奏
        postInvalidateDelayed(mSpeed);
    }
}

配套的 attrs.xml 需要聲明這些屬性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyAF">
        <attr name="AFTopColor" format="color" />
        <attr name="AFDownColor" format="color" />
        <attr name="AFCount" format="integer" />
        <attr name="AFSpeed" format="integer" />
        <attr name="AFOffset" format="dimension" />
    </declare-styleable>
</resources>

佈局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    xmlns:custom="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.afanalog.MainActivity">

    <com.example.customaf.MyAF
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        custom:AFCount="15"
        custom:AFDownColor="@color/down_color"
        custom:AFSpeed="300"
        custom:AFTopColor="@color/top_color"
        custom:AFOffset="15" />
</LinearLayout>

幾點總結

1. 自定義 View 沒有捷徑,但是有路徑。從最簡單的靜態繪製開始,逐步加入隨機數據、延遲重繪、漸變著色,每一步都可獨立驗證。不要一上來就想著寫個萬能的動畫框架。

2. onDraw 是性能敏感區。這個例子刻意把 Paint 的創建放在構造階段、把尺寸計算放在 onSizeChanged,就是為了讓 onDraw 裡只剩繪製語句。真實場景中還可以考慮用 invalidate() 的髒區版本進一步縮小重繪範圍。

3. 若要接真實音頻。可以通過 MediaRecorder.getMaxAmplitude() 週期採樣,或在新版本上用 Visualizer API 獲取頻譜數據。把 Math.random() 換成真實數據源即可,繪製邏輯完全不用改。

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