2

我有一个正在绘制地图指针的自定义地图(画布)。我正在我的主类的 onLocationChanged 方法中更新它,但是我正在努力让位图旋转。getBearing() 似乎不起作用(至少对我来说不起作用),所以我正在努力寻找地图上各点之间的斜率。任何帮助将不胜感激。

public void setBearing(Point prev, Point curr){

  float slope = 1;
  if (prev.x - curr.x !=0){
     slope = (float) ((y1-y2)/(x1-x2));
     bearing = (float) Math.atan(slope);
  }

}

...

Paint p = new Paint();
Matrix matrix = new Matrix();
matrix.postRotate(bearing, coords.x, coords.y);
Bitmap rotatedImage = Bitmap.createBitmap(image, 0, 0, image.getWidth(), 
                                          image.getHeight(), matrix, true);
canvas.drawBitmap(rotatedImage, x-image.getWidth()/2, y-image.getHeight()/2, p);

编辑:

使用纬度和经度坐标找到方位比简单地在两点之间更难。但是,此代码(从此处找到的代码修改)运行良好:

public void setBearing(Location one, Location two){
  double lat1 = one.getLatitude();
  double lon1 = one.getLongitude();
  double lat2 = two.getLatitude();
  double lon2 = two.getLongitude();
  double deltaLon = lon2-lon1;
  double y = Math.sin(deltaLon) * Math.cos(lat2);
  double x = Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(deltaLon);
  bearing = (float) Math.toDegrees(Math.atan2(y, x));
}
4

3 回答 3

2

以下是如何旋转位图:Android:如何根据目标坐标旋转移动的动画精灵

于 2011-05-24T08:50:27.393 回答
2

为了以最小的麻烦和零风险除以正确计算角度,atan2()应该优先于atan(). 以下函数返回相对于 x 轴的非零向量从a到的角度b

public float getBearing(Point a, Point b) { // Valid for a != b.
    float dx = b.x - a.x;
    float dy = b.y - a.y;
    return (float)Math.atan2(dy, dx);
}

我无法就如何将位图旋转给定角度提供建议,因为我不熟悉您的 API。

于 2011-05-23T22:24:03.860 回答
0

如果你想旋转 ImageView

private void rotateImage(ImageView imageView, double angle) {

    Matrix matrix = new Matrix();
    imageView.setScaleType(ScaleType.MATRIX); // required
    matrix.postRotate((float) angle, imageView.getDrawable().getBounds()
            .width() / 2, imageView.getDrawable().getBounds().height() / 2);
    imageView.setImageMatrix(matrix);
}
于 2013-09-11T10:01:23.140 回答