对于如何实现“个人指南针”(即指向特定方位而不是标准“北极”)的指南针, ......不幸的是,我目前的尝试出现了错误(不指向给定的方位)。它还与油门挂钩,以便根据用户转向的方式动态调整自己。像指南针一样旋转ImageView(其他地方设置“北极”)
这是我在它(onSensorChanged()
- 方法是更新箭头)当前的尝试:
public void onSensorChanged(SensorEvent event) {
// If we don't have a Location, we break out
if (LocationObj == null) return;
float azimuth = event.values[0];
float baseAzimuth = azimuth;
GeomagneticField geoField = new GeomagneticField(Double
.valueOf(LocationObj.getLatitude()).floatValue(), Double
.valueOf(LocationObj.getLongitude()).floatValue(),
Double.valueOf(LocationObj.getAltitude()).floatValue(),
System.currentTimeMillis());
azimuth += geoField.getDeclination(); // converts magnetic north into true north
//Correct the azimuth
azimuth = azimuth % 360;
//This is where we choose to point it
float direction = azimuth + LocationObj.bearingTo(destinationObj);
rotateImageView(arrow, R.drawable.arrow, direction);
//Set the field
if(baseAzimuth > 0 && baseAzimuth < 45) fieldBearing.setText("S");
else if(baseAzimuth >= 45 && baseAzimuth < 90) fieldBearing.setText("SW");
else if(baseAzimuth > 0 && baseAzimuth < 135) fieldBearing.setText("W");
else if(baseAzimuth > 0 && baseAzimuth < 180) fieldBearing.setText("NW");
else if(baseAzimuth > 0 && baseAzimuth < 225) fieldBearing.setText("N");
else if(baseAzimuth > 0 && baseAzimuth < 270) fieldBearing.setText("NE");
else if(baseAzimuth > 0 && baseAzimuth < 315) fieldBearing.setText("E");
else if(baseAzimuth > 0 && baseAzimuth < 360) fieldBearing.setText("SE");
else fieldBearing.setText("?");
}
及这里的旋转ImageView的(rotateImageView()
)的方法:
private void rotateImageView(ImageView imageView, int drawable, float rotate) {
// Decode the drawable into a bitmap
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
drawable);
// Get the width/height of the drawable
DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = bitmapOrg.getWidth(), height = bitmapOrg.getHeight();
// Initialize a new Matrix
Matrix matrix = new Matrix();
// Decide on how much to rotate
rotate = rotate % 360;
// Actually rotate the image
matrix.postRotate(rotate, width, height);
// recreate the new Bitmap via a couple conditions
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width, height, matrix, true);
//BitmapDrawable bmd = new BitmapDrawable(rotatedBitmap);
//imageView.setImageBitmap(rotatedBitmap);
imageView.setImageDrawable(new BitmapDrawable(getResources(), rotatedBitmap));
imageView.setScaleType(ScaleType.CENTER);
}
任何帮助非常感谢,因为我不知道如何继续。我在试用时得到的“读数”有些不准确,并指向了错误的方向。我是否真的做了一些事情,还是我的测试运行非常糟糕?
请问更新图像这种方法是否过CPU-costy?当我遵循代码时,屏幕非常慢,我甚至无法放大或缩小。 –
@ perfectionm1ng我没有注意到那样的事情,那已经差不多两年了。可能是事物的组合? :-) – ninetwozero