編輯:關於 Android 程式設計
SurfaceView 是 Android 中極為重要的繪圖容器,它的圖像繪製被放在主線程之外的另一個線程中完成,除了繪圖,還能用來播放視頻。本文就用它來繪製一個會隨手機朝向轉動的指南針。
實現自定義 SurfaceView,需要新建一個繼承自 SurfaceView 的類,並重寫至少一種構造器。在構造器中,要透過 getHolder() 拿到一個 SurfaceHolder 對象 holder;canvas 畫布由 holder 調用 lockCanvas() 鎖定並取得,用完後再用 unlockCanvasAndPost(canvas) 解鎖。構造方法裡,holder 還必須透過 addCallback() 註冊監聽器,其中有三個方法需要實現:surfaceCreated()、surfaceChanged()、surfaceDestroyed()。自定義 SurfaceView 的圖像繪製則放在 surfaceCreated() 中進行。
下面用 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);
}
}
效果演示(必須在真機上才能運行,因為模擬器沒有真實傳感器數據):
看到沒,這個指南針簡約又大氣。
用 SurfaceView 與属性動畫打造彈跳小球載入動畫
先看效果 這個動畫看起來簡單,真要做得自然卻需要幾個知識點配合: 1. 属性動畫(ValueAnimator / AnimatorSet) 2. Path 與 Canv
Android SQLite 入門:DbHelper、CRUD 與 Spinner 資料綁定
SQLite 是 Android 內建的輕量級關聯式資料庫,適合儲存本地結構化資料。開發時通常會建立 SQLiteOpenHelper,負責建立與升級資料表。 建立資料
Android 自訂下拉篩選 Dialog 實作(一)
想要做出如圖所示的彈出式 Dialog,第一步是先把它的樣式定義好: <style name=DropdownFilterDialogStyle parent=@a
Android VectorDrawable 向量圖教學:路徑、填色與動畫
從位圖到向量圖 png、jpg 等位圖由像素組成,放大後容易失真。VectorDrawable 以點、線、路徑與填色描述圖形,可任意縮放而不影響清晰度,也能減少部分圖形資