【问题标题】:Get the rotate value from matrix in android?从android中的矩阵获取旋转值?
【发布时间】:2012-08-28 17:19:23
【问题描述】:

如何从平移/缩放/旋转矩阵中旋转值?

Matrix matrix = new Matrix();
matrix.postScale(...);
matrix.postTranslate(...);
matrix.postRotate(...);
...

现在我不知道rotate 是什么,但我需要得到它。如何做到这一点?

【问题讨论】:

标签: android matrix rotation


【解决方案1】:

不幸的是,没有定义提取旋转信息的方法(我假设您正在寻找度数)。您可以做的最好的事情是使用getValues 提取矩阵值并使用转换公式(类似于在this 页面底部讨论的内容)来尝试找出角度。

【讨论】:

  • 那个页面很有用,我现在明白了。
【解决方案2】:
float[] v = new float[9];
matrix.getValues(v);
// translation is simple
float tx = v[Matrix.MTRANS_X];
float ty = v[Matrix.MTRANS_Y];

// calculate real scale
float scalex = v[Matrix.MSCALE_X];
float skewy = v[Matrix.MSKEW_Y];
float rScale = (float) Math.sqrt(scalex * scalex + skewy * skewy);

// calculate the degree of rotation
float rAngle = Math.round(Math.atan2(v[Matrix.MSKEW_X], v[Matrix.MSCALE_X]) * (180 / Math.PI));

从这里 http://judepereira.com/blog/calculate-the-real-scale-factor-and-the-angle-of-rotation-from-an-android-matrix/

【讨论】:

  • 比标记的答案好得多。谢谢!它有效。
  • 我使用 float rAngle = Math.round(Math.atan2(v[Matrix.MSKEW_X], v[Matrix.MSCALE_X]) * (180 / Math.PI)) 计算了旋转需要乘以 -1 才能得到正确的值。为什么会这样?
  • 这一行中的“值”是什么....float scalex = values[Matrix.MSCALE_X];它的意思是“v”吗?
  • 我的比例因子有误。这个比例因子在缩放后减小了图像大小。还有其他方法可以获得比例因子吗?
  • scaleX 和 scaleY 取值不同时,计算出的度数不完美。
【解决方案3】:

我不能在这里输入方程式,所以我画了一张如何解决您的问题的图片。这里是:

【讨论】:

  • 有什么方法可以为矩阵设置旋转,因为当我应用旋转时它会重置整个矩阵,让我告诉你:之前:{[0.38719338, -0.035239104, 9.199848] [0.035239104, 0.38719338, -24.01611] [0.0, 0.0, 1.0]} 添加旋转后matrix.setRotate(0); 矩阵值会像:{[1.0, -0.0, 0.0] [0.0, 1.0, 0.0] [0.0, 0.0, 1.0]}
【解决方案4】:

除了之前的答案,这里是您需要的 Kotlin 扩展。 它返回这个矩阵的旋转角度值

fun Matrix.getRotationAngle() = FloatArray(9)
    .apply { getValues(this) }
    .let { -round(atan2(it[MSKEW_X], it[MSCALE_X]) * (180 / PI)).toFloat() }

只需要在你的矩阵上调用它。请注意,您的矩阵值不会更改。

val angleInDegree = yourMatrix.getRotationAngle()

【讨论】:

    【解决方案5】:

    这是@Evansgelist 为 Kotlin 用户提供的答案的更方便的实现:

    val Matrix.rotation: Float
        get() {
            return atan2(
                values()[Matrix.MSKEW_X],
                values()[Matrix.MSCALE_X],
            ) * (180f / Math.PI.toFloat())
        }
    
    val Matrix.scale: Float
        get() {
            return sqrt(
            values()[Matrix.MSCALE_X].pow(2) +
                values()[Matrix.MSKEW_Y].pow(2)
            )
        }
    
    val Matrix.translationX: Float
        get() { return values()[Matrix.MTRANS_X] }
    
    val Matrix.translationY: Float
        get() { return values()[Matrix.MTRANS_Y] }
    

    请注意,每次调用 values 都会分配一个新的 FloatArray

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      相关资源
      最近更新 更多