【问题标题】:Rotate Matrix for bitmap - Android旋转位图矩阵 - Android
【发布时间】:2011-08-31 11:49:30
【问题描述】:

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

【问题讨论】:

    标签: android matrix bitmap bearing


    【解决方案1】:

    【讨论】:

    • 感谢您的链接。你知道 - 角度是北东度数,还是弧度(或者是别的什么)?
    • 角度以度为单位,其余的你试一试就会很容易找到。
    • 伟大而简单的解决方案!此外,我的方位代码不起作用的一个原因是我正在使用纬度/经度坐标。我找到了一个简单的解决方法(我会更新我的帖子)。
    • 酷,我必须收藏它,以备日后需要时使用。我看到你找到了 Math.toDegrees() 函数 - 很高兴知道。您的 atan2 会产生 0-90 或 0-360 的角度吗?我必须在我的链接中手动调整它。
    • 看起来我的角度从 -180 到 180,这真的很容易。
    【解决方案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。

    【讨论】:

    • 感谢您的反馈。我想知道如何使用 atan2,所以这很有帮助。
    • antonakos,atan2 是正确的方法,但由于我使用的是纬度/经度坐标,这使问题变得更加困难。要发布代码,我将更新我上面的帖子以添加此轴承代码。感谢您的帮助
    【解决方案3】:

    如果你想旋转 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 1970-01-01
      • 2014-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多