我正在写一个Android应用程序,其中一个功能是地图将根据指南针旋转(即,如果手机指向东方,地图将被定向,以便地图的东侧在顶部)。我之前发现的答案建议在mapView中编写onDraw()方法,但是,api将该方法更改为final,因此它不能被覆盖。因此,我尝试覆盖dispatchDraw()
方法,如下所示:
注意:
-compass是一个布尔值,如果为true,则旋转视图
-bearing是一个浮点变量,它具有视图应旋转的度数
protected void dispatchDraw(Canvas canvas) {
canvas.save();
if (compass) {
final float w = this.getWidth();
final float h = this.getHeight();
final float scaleFactor = (float)(Math.sqrt(h * h + w * w) / Math.min(w, h));
final float centerX = w / 2.0f;
final float centerY = h / 2.0f;
canvas.rotate(bearing, centerX, centerY);
canvas.scale(scaleFactor, scaleFactor, centerX, centerY);
}
super.dispatchDraw(canvas);
canvas.restore();
}
发布于 2010-06-28 04:54:12
它应该是这样的:
@Override
protected void dispatchDraw(Canvas canvas) {
canvas.save(Canvas.MATRIX_SAVE_FLAG);
if (compass) {
// rotate the canvas with the pivot on the center of the screen
canvas.rotate(-azimuth, getWidth() * 0.5f, getHeight() * 0.5f);
super.dispatchDraw(canvas);
canvas.restore();
}
}
发布于 2012-01-31 00:40:56
看看ANDROID_SDK\add-ons\addon-google_apis-google_inc_-7\samples\MapsDemo
中的MapsDemo示例。它有旋转贴图演示。
发布于 2015-01-14 16:11:04
此答案适用于Google Maps api v2
。可以通过向传感器侦听器注册您的应用程序来定位,并在onSensorChanged
内获得相对于真北的角度,并相应地更新相机。角度可以用于轴承。可以使用以下代码:
尝试使用getOrinetation Sensor.TYPE_ORIENTATION
,而不是使用api。Sensor.TYPE_ORIENTATION
已被弃用。
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (sensorManager != null)
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_GAME);
}
public void onSensorChanged(SensorEvent event) {
float degree = Math.round(event.values[0]);
Log.d(TAG, "Degree ---------- " + degree);
updateCamera(degree);
}
private void updateCamera(float bearing) {
CameraPosition oldPos = googleMap.getCameraPosition();
CameraPosition pos = CameraPosition.builder(oldPos).bearing(bearing)
.build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(pos));
}
https://stackoverflow.com/questions/1830391
复制相似问题