旋转矩阵的位图 - Android

时间:2011-05-23 21:34:02

标签: android matrix bitmap bearing

我有一个自定义地图(画布),我正在绘制地图指针。我在我的主类的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);

编辑:

使用纬度和经度坐标来寻找方位比单纯地在两点之间更难。但是,此代码(从找到的代码here修改)效果很好:

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));
}

3 个答案:

答案 0 :(得分:2)

要以最小的风险和除以零的风险正确计算角度,atan2()应优先于atan()。以下函数返回从ab的非零向量相对于x轴的角度:

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。

答案 1 :(得分:2)

答案 2 :(得分: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);
}