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

高仿 To 圈註冊錄音界面:自定義 View 全解析

編輯:關於 Android 程式設計

先看一眼 To 圈(QQ、微信等大部分 IM 也是大同小異)註冊頁的錄音效果:

為了還原這個效果,確實花了不少功夫。回頭總結,主要難點有三處:

難點一:隨音量變化的話筒

這是最讓人頭疼的部分。最初的三條路都被堵死了:

用圖片?想達到最終效果需要 12 張圖幀,內存和資源開銷太大,直接放棄。

用遮罩?仔細觀察會發現話筒圓形進度條外圈是透明的,遮罩必須與底圖完美重合,而「完美重合」意味著要處理屏幕適配,又是一個大坑。

最後採用的方案略有取巧:用一個豎向 ProgressBar 承擔話筒的進度填充,下面的 Y 字形「把手」則直接用 Canvas 畫出來。為了讓線條比例看起來像真話筒,做了大量三角函數與像素計算。這個方案的好處是規避了適配問題,也不必加載一堆圖幀輪播;但它肯定不是最優解,如果讀者有更高雅的思路,非常歡迎交流。

難點二:外圈藍色計時圓弧

錄音過程中一圈藍色弧線隨時間遞增,本質是一個自繪的圓弧,只需要控制終止角度。

難點三:手勢判斷

手指上劃超過閾值時,界面要從「話筒」切換成「垃圾桶」並提示鬆手取消。這部分依賴 onTouch 中的 Y 座標判斷。

做完之後的體會是:難點一一個就比二和三加起來還難。

界面結構

註冊頁布局 activity_register.xml 中,用 <include> 引入錄音浮層,默認隱藏:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 錄音顯示 UI 層 -->
    <include
        android:id="@+id/layout_register_popup"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:visibility="gone"
        layout="@layout/layout_recode_popwindow" />
</RelativeLayout>

黑色錄音框 layout_recode_popwindow.xml,核心是那個自定義的圓形 View:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="180dp"
        android:layout_height="180dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/shape_register_recoderlayout">

        <com.whale.nangua.toquan.view.recodepopwindow.RecodePopWindowCircle
            android:id="@+id/circleview_register_microphone"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="20dp"
            android:background="@drawable/shape_register_recodepopwindow" />

        <TextView
            android:id="@+id/tv_register_show"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="10dp"
            android:gravity="center"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:text="手指上劃,取消發送"
            android:textColor="@android:color/white"
            android:textSize="16sp" />
    </RelativeLayout>
</RelativeLayout>

效果如下:

核心自定義 View:RecodePopWindowCircle

這個 View 繼承 RelativeLayout,在 onDraw 中完成三件事:畫 Y 字形把手、畫外圈藍色計時弧、根據狀態切換垃圾桶圖標。

public class RecodePopWindowCircle extends RelativeLayout {

    private ProgressBar progressbar_register_recode; // 豎向進度條
    private int width;   // 控制項總寬
    private int height;  // 控制項總高
    private boolean IS_SHOW_RECODING = true; // 是否顯示話筒
    private int endArc = 0;                  // 圓弧終止角度
    private float scale;                     // 屏幕密度

    public RecodePopWindowCircle(Context context, AttributeSet attrs) {
        super(context, attrs);
        scale = getResources().getDisplayMetrics().density;
        LayoutInflater.from(context).inflate(R.layout.layout_recode_circlepopwindow, this, true);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        progressbar_register_recode = (ProgressBar) findViewById(R.id.progressbar_register_recode);
        width = getWidth();
        height = getHeight();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();

        if (IS_SHOW_RECODING) {
            progressbar_register_recode.setVisibility(View.VISIBLE);
            drawMicrophone(canvas, paint);   // 畫 Y 字形把手
        } else {
            progressbar_register_recode.setVisibility(View.INVISIBLE);
            drawTrash(canvas);               // 畫垃圾桶
        }

        // 外圈藍色錄音圓弧
        paint.setColor(Color.parseColor("#0CA6D9"));
        paint.setStrokeWidth(2);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        canvas.drawArc(new RectF(2, 2, width - 2, height - 2), -90, endArc, false, paint);
    }

    /** 畫話筒的 Y 形把手:一段弧 + 一條豎線 + 三個小圓點 */
    private void drawMicrophone(Canvas canvas, Paint paint) {
        paint.setColor(Color.WHITE);
        paint.setStrokeWidth(6);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);

        int center = width / 2;
        int r = (int) (8 * scale);        // 進度條底部半徑
        int space = (int) (5 * scale);    // 圓弧與進度條的間隔
        int offset = (int) (5 * scale);   // 整體下移

        RectF oval = new RectF();
        oval.left   = center - r - space;
        oval.top    = center - 2 * r - space + offset;
        oval.right  = center + r + space;
        oval.bottom = center + space + offset;

        canvas.drawArc(oval, 20, 140, false, paint);

        int lineLength = (int) (10 * scale);
        canvas.drawLine(center, center + space + offset,
                        center, center + space + lineLength + offset, paint);

        // 三個端點加白色小圓點,讓造型更飽滿
        int pointx = (int) (Math.cos(center) + r + space);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(center + pointx - 1 * scale, center + 2 * scale, 3, paint);
        canvas.drawCircle(center - pointx + 1 * scale, center + 2 * scale, 3, paint);
        canvas.drawCircle(center, center + space + lineLength + offset, 3, paint);
    }

    /** 上劃取消狀態下顯示垃圾桶 */
    private void drawTrash(Canvas canvas) {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_trash);
        canvas.drawBitmap(bitmap, null,
            new Rect((int) (width / 2 - 20 * scale), (int) (height / 2 - 25 * scale),
                     (int) (width / 2 + 20 * scale), (int) (height / 2 + 25 * scale)), null);
    }

    /** 是否顯示錄音話筒 */
    public void setIsShowRecoding(boolean isShowRecoding) {
        this.IS_SHOW_RECODING = isShowRecoding;
        postInvalidate();
    }

    /** 設置計時圓弧的終止角度 */
    public void setEndArc(int endArc) {
        this.endArc = endArc;
        postInvalidate();
    }

    /** 設置音量進度 */
    public void setProgress(int progress) {
        progressbar_register_recode.setProgress(progress);
    }
}

這個自定義 View 對外只暴露三個方法:setProgress(音量)、setEndArc(計時)、setIsShowRecoding(狀態切換),封裝得算是乾淨。

控制層:RegisterActivity

Activity 這邊的工作是把三條時間線匯到一起:音量採樣、計時弧遞增、超時停止。

public class RegisterActivity extends Activity implements View.OnClickListener,
        RadioGroup.OnCheckedChangeListener, SoundMeter.onStartRecoder {

    private RecodePopWindowCircle circleview_register_microphone;
    private TextView tv_register_show;
    private ImageButton imgbtn_register_recode;
    private View layout_register_popup;

    private SoundMeter mSensor;                 // 錄音組件
    private Handler mHandler = new Handler();

    private static final int POLL_INTERVAL = 300;         // 音量採樣間隔
    private static final int UPDATE_ARC_INTERVAL = 200;   // 圓弧更新間隔
    private boolean IF_CANCLE_SEND = false;

    /** 週期性讀取振幅,更新話筒進度 */
    private Runnable ampTask = new Runnable() {
        @Override
        public void run() {
            double amp = mSensor.getAmplitude();
            updateDisplay(amp);
            mHandler.postDelayed(ampTask, POLL_INTERVAL);
        }
    };

    /** 週期性推進計時圓弧 */
    private Runnable updateArcTask = new Runnable() {
        @Override
        public void run() {
            endArc += 1;
            circleview_register_microphone.setEndArc(endArc);
            mHandler.postDelayed(updateArcTask, UPDATE_ARC_INTERVAL);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
    }

    private void initView() {
        screenHeight = getWindowManager().getDefaultDisplay().getHeight();
        scale = getResources().getDisplayMetrics().density;

        tv_register_show = (TextView) findViewById(R.id.tv_register_show);
        layout_register_popup = findViewById(R.id.layout_register_popup);
        layout_register_popup.setVisibility(View.INVISIBLE);
        circleview_register_microphone =
                (RecodePopWindowCircle) findViewById(R.id.circleview_register_microphone);

        mSensor = new SoundMeter();
        mSensor.setonStartRecoderCallback(this);

        imgbtn_register_recode = (ImageButton) findViewById(R.id.imgbtn_register_recode);
        imgbtn_register_recode.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int Y = (int) event.getRawY();
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        layout_register_popup.setVisibility(View.VISIBLE);
                        circleview_register_microphone.setEndArc(0);
                        startVoiceT = System.currentTimeMillis();
                        voiceName = startVoiceT + ".amr";
                        start(voiceName);
                        break;

                    case MotionEvent.ACTION_UP:
                        layout_register_popup.setVisibility(View.GONE);
                        endArc = 0;
                        stop();
                        if (IF_CANCLE_SEND) {
                            // TODO 取消發送
                        } else {
                            // TODO 發送音頻
                        }
                        break;

                    case MotionEvent.ACTION_MOVE:
                        // 手指越過閾值 → 切換為「鬆手取消」
                        if (Y <= screenHeight / 2 + 90 * scale) {
                            tv_register_show.setText("手指鬆開,取消發送");
                            tv_register_show.setBackground(
                                    getResources().getDrawable(R.drawable.shape_register_recodetv));
                            circleview_register_microphone.setIsShowRecoding(false);
                        } else {
                            tv_register_show.setText("手指上劃,取消發送");
                            tv_register_show.setBackground(null);
                            circleview_register_microphone.setIsShowRecoding(true);
                        }
                        break;
                }
                return true;
            }
        });
    }

    /** 把振幅映射成 12 檔進度 */
    private void updateDisplay(double signalEMA) {
        int temp = 100 / 12;
        int level = (int) signalEMA + 1;
        if (level < 1) level = 1;
        if (level > 12) level = 12;
        circleview_register_microphone.setProgress(level * temp);
    }

    private void start(String name) {
        mSensor.start(name);
        mHandler.postDelayed(ampTask, POLL_INTERVAL);
        mHandler.postDelayed(updateArcTask, UPDATE_ARC_INTERVAL);
    }

    private void stop() {
        mHandler.removeCallbacks(mSleepTask);
        mHandler.removeCallbacks(ampTask);
        mHandler.removeCallbacks(updateArcTask);
        mSensor.stop();
        circleview_register_microphone.setProgress(0);
    }
}

錄音本身用的是 MediaRecorder 的封裝類 SoundMeter,那部分比較常規,這裡不再展開。

最終效果

總體來說功能不算難實現,但自繪部分對比例、密度、抗鋸齒的處理很考驗耐心。經驗不足時容易反覆返工——這大概也是自定義 View 的常態吧。需要完整源碼的可以在評論區留言。

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