編輯: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 會自動呼叫對應的建構子。
核心畫法是這樣的:把畫布寬度當成橫軸,每一個 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 就是螢幕寬度內塞三個波。原例另外實作了 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() 中收尾,避免不必要的電量與效能消耗。
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() 要求重繪。把公式換成任何其他函數,同一套骨架都能沿用。
Android 本地化實戰:讓 App 說出使用者的語言
同一支 App,可能會在幾十個國家的裝置上執行。要讓它在不同市場都顯得自然,就不能把文字硬寫在程式碼裡,而必須處理語言環境(Locale)造成的差異——不只是文字,還包含
Android JSON 解析實戰:從回應中取出你要的那幾個欄位
JSON(JavaScript Object Notation)早已成為應用程式之間交換資料的通用語言。相較於 XML,它沒有大量冗餘的封閉標籤,結構輕量、可讀性高,行動
Android ContentProvider 使用指南:共享資料與 URI 設計
ContentProvider 用於對外共享資料,其他應用可透過 ContentResolver 進行增刪改查。註冊時需設定 authorities,外部則以 conte
Android 多語系支援:用 values-it 讓 App 換上當地語言
一支 App 上線後,可能同時被十幾個國家的使用者開啟。若畫面上的文字全是硬編碼的英文,對非英語使用者而言體驗打了折扣。Android 從架構層面就支援資源切換:你只要按