Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 自訂 View 實作:用 Canvas 畫出可互動的正弦波

編輯:Android 開發實例

正弦波是訊號處理與物理課程的常客,但把它畫在 Android 畫面上,其實是一次很好的 Canvas 與自訂 View 練習。本文從零示範:輸入頻率、相位與振幅,按下滑鈕後重新繪製波形,點擊畫面還能讀取座標。

一、先把介面搭起來

版面由上方三列輸入欄與下方一塊自訂 View 組成。三個 EditText 分別對應頻率(赫茲)、相位(度)與振幅,最後放一顆「產生波形」按鈕;按鈕下方掛上自己寫的 com.kernel.minthen.SineWave,它就是畫布。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView android:text="頻率:"
            android:textSize="20sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <EditText android:id="@+id/frequency"
            android:textSize="20sp"
            android:layout_width="75dip"
            android:layout_height="wrap_content"
            android:text="3"/>
        <TextView android:text="赫茲"
            android:textSize="20sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>

    <!-- 相位列:@+id/phase,預設 30.0 -->
    <!-- 振幅列:@+id/amplifier,預設 100 -->

    <Button android:id="@+id/wave"
        android:textSize="20sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="產生波形"/>

    <com.kernel.minthen.SineWave
        android:id="@+id/sine"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

自訂 View 在 XML 中使用的寫法,就是「完整類別名稱」當標籤,Android 會自動呼叫對應的建構子。

二、SineWave:把公式變成線段

核心畫法是這樣的:把畫布寬度當成橫軸,每一個 x 座標代入正弦函數算出 y,再用 canvas.drawLine() 把相鄰兩點連起來。點夠密,線段自然看起來像平滑曲線。

public class SineWave extends View implements Runnable {

    private Paint mPaint;
    private float amplifier = 100.0f;   // 振幅
    private float frequency = 2.0f;     // 頻率(Hz)
    private float phase = 45.0f;        // 相位(度)
    private int width, height;
    private float px = -1, py = -1;

    // 少了這個兩參數建構子,XML 膨脹時會出現
    // "custom view SineWave is not using the 2- or 3-argument
    //  View constructors" 的錯誤
    public SineWave(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
    }

    public void setParam(float amplifier, float frequency, float phase) {
        this.amplifier = amplifier;
        this.frequency = frequency;
        this.phase = phase;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.WHITE);
        width = getWidth();
        height = getHeight();

        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.GREEN);
        mPaint.setAlpha(200);
        mPaint.setStrokeWidth(5);

        // 振幅若超出畫布高度,就收斂到畫布半高,避免波形被裁掉
        if (amplifier * 2 > height) {
            amplifier = height / 2f;
        }
        float cy = height / 2f;   // 中線

        for (int i = 0; i < width - 1; i++) {
            float y1 = cy - amplifier * (float) Math.sin(
                    phase * 2 * Math.PI / 360.0f + 2 * Math.PI * frequency * i / width);
            float y2 = cy - amplifier * (float) Math.sin(
                    phase * 2 * Math.PI / 360.0f + 2 * Math.PI * frequency * (i + 1) / width);
            canvas.drawLine(i, y1, i + 1, y2, mPaint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        px = event.getX();
        py = event.getY();
        invalidate();
        return super.onTouchEvent(event);
    }
}

三個細節值得說明:

  • 相位換算:輸入是「度」,所以先乘 2π/360 轉成弧度才能丟進 Math.sin()。
  • 頻率的意義:用 frequency * i / width 當橫向參數,代表整段畫布橫跨幾個週期;頻率 3 就是螢幕寬度內塞三個波。
  • 振幅夾限:使用者輸入過大值時波形會超出畫布,因此在 onDraw 中做一次收斂。

三、觸摸座標與週期性重繪

原例另外實作了 Runnable,在背景執行緒每 1000 毫秒呼叫一次 postInvalidate(),讓畫面持續刷新;同時在 onDraw() 中比對觸點是否落在波線附近(前後 2.5 像素的容差),若是就用紅字把座標標在左上角,並用藍字在左下角常駐顯示目前座標。

@Override
public void run() {
    while (!Thread.currentThread().isInterrupted()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        postInvalidate();
    }
}

這裡有個值得留意的設計問題:在自訂 View 建構子裡直接 new Thread(this).start() 並不容易停止,View 被回收後執行緒仍在跑。實務上更乾淨的做法是改用 Handler + postDelayed(),或搭配 Choreographer 與 onDetachedFromWindow() 中收尾,避免不必要的電量與效能消耗。

四、Activity 端把參數接上

public class mySine extends Activity {

    private EditText frequency, phase, amplifier;
    private SineWave sw;

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

        sw = (SineWave) findViewById(R.id.sine);
        frequency = (EditText) findViewById(R.id.frequency);
        phase = (EditText) findViewById(R.id.phase);
        amplifier = (EditText) findViewById(R.id.amplifier);

        findViewById(R.id.wave).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sw.setParam(
                    Float.parseFloat(amplifier.getText().toString()),
                    Float.parseFloat(frequency.getText().toString()),
                    Float.parseFloat(phase.getText().toString()));
            }
        });
    }
}

輸入欄在 onStart() 時回填目前參數,按下按鈕後再把新值推給 SineWave,就完成了一個可即時調整的波形產生器。正式版本建議替 parseFloat() 加上例外處理,並用 SeekBar 取代文字輸入,操作手感會好上不少。

這個例子示範了自訂 View 的三個基本要素:在 onMeasure/onDraw 的體系中取得寬高、用 Paint 描述外觀、以 invalidate() 要求重繪。把公式換成任何其他函數,同一套骨架都能沿用。

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