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

自定義 SurfaceView 結合傳感器:手繪指南針實戰

編輯:關於 Android 程式設計

概述

SurfaceView 是 Android 中極為重要的繪圖容器,它的圖像繪製被放在主線程之外的另一個線程中完成,除了繪圖,還能用來播放視頻。本文就用它來繪製一個會隨手機朝向轉動的指南針。

實現方法

實現自定義 SurfaceView,需要新建一個繼承自 SurfaceView 的類,並重寫至少一種構造器。在構造器中,要透過 getHolder() 拿到一個 SurfaceHolder 對象 holder;canvas 畫布由 holder 調用 lockCanvas() 鎖定並取得,用完後再用 unlockCanvasAndPost(canvas) 解鎖。構造方法裡,holder 還必須透過 addCallback() 註冊監聽器,其中有三個方法需要實現:surfaceCreated()、surfaceChanged()、surfaceDestroyed()。自定義 SurfaceView 的圖像繪製則放在 surfaceCreated() 中進行。

Demo:結合加速度與地磁傳感器

下面用 SurfaceView 繪製指南針模型,並結合加速度傳感器和地磁傳感器讓它隨手機朝向轉動:

public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder holder;
    private Canvas canvas;
    private Path path;
    private Paint mPaintCircle, mPaintLine, mPaintText;
    private int width, height;
    private float degree;
    private boolean isDrawing = true;
    private SensorManager sensorManager;
    private float lastDegree;

    public MySurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        width = 1100;
        height = 1500;
        // 得到 SurfaceHolder 對象
        holder = getHolder();
        // 添加 Callback 監聽器
        holder.addCallback(this);
        // path 用於畫指針
        path = new Path();
        // 畫外環的畫筆
        mPaintCircle = new Paint();
        mPaintCircle.setColor(Color.BLACK);
        mPaintCircle.setStyle(Paint.Style.FILL_AND_STROKE);
        mPaintCircle.setStrokeWidth(30);
        // 畫刻度線的畫筆
        mPaintLine = new Paint();
        mPaintLine.setColor(Color.WHITE);
        mPaintLine.setStyle(Paint.Style.FILL);
        mPaintLine.setStrokeWidth(10);
        // 畫文本的畫筆
        mPaintText = new Paint();
        mPaintText.setTextSize(70);
        mPaintText.setColor(Color.WHITE);
        // 管理傳感器
        sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        Sensor magneticSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(listener, magneticSensor, SensorManager.SENSOR_DELAY_GAME);
        sensorManager.registerListener(listener, accelerometerSensor, SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    public void surfaceCreated(final SurfaceHolder holder) {
        // 在單獨線程中繪製
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isDrawing) {
                    canvas = holder.lockCanvas();
                    canvas.drawColor(Color.BLUE);
                    canvas.drawCircle(width / 2, height / 2, 400, mPaintCircle);
                    for (int i = 0; i <= 35; i++) {
                        canvas.save();
                        canvas.rotate(10 * i + degree, width / 2, height / 2);
                        canvas.drawLine(width / 2, height / 2 - 400,
                                width / 2, height / 2 - 400 + 50, mPaintLine);
                        if (i == 0) canvas.drawText("N", width / 2, height / 2 - 440, mPaintText);
                        else if (i == 8) canvas.drawText("E", width / 2, height / 2 - 440, mPaintText);
                        else if (i == 17) canvas.drawText("S", width / 2, height / 2 - 440, mPaintText);
                        else if (i == 26) canvas.drawText("W", width / 2, height / 2 - 440, mPaintText);
                        canvas.restore();
                    }
                    // degree 改變時,畫布轉動相應角度
                    canvas.rotate(degree, width / 2, height / 2);
                    // 繪製指針
                    path.moveTo(width / 2 - 10, height / 2);
                    path.lineTo(width / 2, height / 2 - 150);
                    path.lineTo(width / 2 + 10, height / 2);
                    path.close();
                    canvas.drawPath(path, mPaintLine);
                    // 用完 canvas 要解鎖
                    holder.unlockCanvasAndPost(canvas);
                }
            }
        }).start();
    }

    @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // 停止線程死循環,並注銷傳感器監聽
        isDrawing = false;
        if (sensorManager != null) {
            sensorManager.unregisterListener(listener);
        }
    }

    // 傳感器監聽
    private SensorEventListener listener = new SensorEventListener() {
        float[] accelerometerValues = new float[3];
        float[] magneticValues = new float[3];

        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                accelerometerValues = event.values.clone();
            } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                magneticValues = event.values.clone();
            }
            float[] R = new float[9];
            float[] values = new float[3];
            // 得到旋轉矩陣
            SensorManager.getRotationMatrix(R, null, accelerometerValues, magneticValues);
            // 計算手機旋轉數據
            SensorManager.getOrientation(R, values);
            // 弧度轉角度
            degree = -(float) Math.toDegrees(values[0]);
            if (Math.abs(degree - lastDegree) > 10) {
                lastDegree = degree;
            }
        }

        @Override public void onAccuracyChanged(Sensor sensor, int accuracy) {}
    };
}

在 xml 布局中定義這個自定義 SurfaceView:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <com.example.administrator.selfishgroupview.my_groupview.MySurfaceView
        android:id="@+id/my_surfaceView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

主活動:

public class SouthArrowActivity extends Activity {
    private MySurfaceView mySurfaceView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_source);
        mySurfaceView = (MySurfaceView) findViewById(R.id.my_surfaceView);
    }
}

效果演示(必須在真機上才能運行,因為模擬器沒有真實傳感器數據):

看到沒,這個指南針簡約又大氣。

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