在旧矩阵android

时间:2016-08-07 06:29:04

标签: android math matrix rotation imageview

我有一个转换图像的矩阵。旧矩阵是尺度和平移的函数。 现在,如何在旧Matrix中从中心应用旋转,而不影响其他变换,如缩放和平移。

我已经尝试了这个

    //get old matrix    
    Matrix matrix = getImageMatrix();

    float tx = getMatrixValue(matrix, Matrix.MTRANS_X);
    float ty = getMatrixValue(matrix, Matrix.MTRANS_Y);

    float scaleX = getMatrixValue(matrix, Matrix.MSCALE_X);
    float scaleY = getMatrixValue(matrix, Matrix.MSCALE_Y);

    float skewX = getMatrixValue(matrix, Matrix.MSKEW_X);
    float skewY = getMatrixValue(matrix, Matrix.MSKEW_Y);

    //calculating the actual scale
    float sx = (float)Math.sqrt((scaleX*scaleX)+(skewY*skewY));
    float sy = (float)Math.sqrt((scaleY*scaleY)+(skewX*skewX));

    //calculating the rotateAngle
    float rAngle = Math.round(Math.atan2(scaleX, skewX) * (180 / Math.PI));



    //calculate the actual width and height of image
    float width = sx * drawable.getIntrinsicWidth();
    float height = sy * drawable.getIntrinsicHeight();

    //calculate the center pivot for rotation
    float cx = (width/2)+tx;
    float cy = (height/2)+ty;

    //Applying Rotation from center pivot
    matrix.postTranslate(-cx , -cy);
    matrix.postRotate(rotateAngle, (width/2)+tx, (height/2)+ty);
    matrix.postTranslate(cx, cy);

    setImageMatrix(matrix);

    invalidate();

我没有得到旋转的渴望结果。它改变了翻译。我在这做了什么错...?

查看完整代码(第220行以后) http://pastebin.com/NWrNw0Nd

2 个答案:

答案 0 :(得分:2)

这是你如何做到的。简短又甜蜜。

    private RectF rect = new RectF();   // only allocate once

    public void rotate(int rotateAngle) {

        if (rotateAngle % 90 != 0) {
            throw new IllegalArgumentException("angle must be a multiple of 90 degrees");
        }

        Matrix matrix = getImageMatrix();

        // get the original dimensions of the drawable
        rect.set(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());

        // calculate where the current matrix has put the image
        matrix.mapRect(rect);  // rect now has updated coordinates

        // rotate pivoting on the center point
        matrix.postRotate(rotateAngle, rect.centerX(), rect.centerY());
        setImageMatrix(matrix); // i think setImageMatrix() will call invalidate() itself
    }

答案 1 :(得分:1)

我不是100%肯定,但我认为问题在于您尝试提取然后重新应用tx和ty值。矩阵有点“记住”已经完成的事情,所以如果你使用postRotate / postTranslate / post *函数则没有必要。尝试这样的事情:

Matrix matrix = getImageMatrix();
float rotateAngle = 90.0;  // or whatever

//calculate the actual width and height of image
float width = drawable.getIntrinsicWidth();
float height = drawable.getIntrinsicHeight();

//calculate the center pivot for rotation
float cx = (width/2);
float cy = (height/2);

//Applying Rotation from center pivot
matrix.postTranslate(-cx , -cy);
matrix.postRotate(rotateAngle);
matrix.postTranslate(cx, cy);
setImageMatrix(matrix);

invalidate();

我相信你会围绕中心旋转90度。

相关问题