Android 可旋转的 ImageView

7

我正在尝试创建一个可旋转的ImageView,我将指定某个角度和中心点,并在该中心点周围旋转。我尝试了类似以下的代码:

Matrix matrix = new Matrix();
matrix.postRotate(45, imageView.getWidth(), imageView.getHeight());
imageView.setScaleType(ScaleType.MATRIX);
imageView.setImageMatrix(matrix);

但是postRotate方法的参数(第二和第三个参数-旋转中心点)根本没有任何变化。即使它们是0, 0-也是一样的。

因此,我想创建一个ImageView,在初始化时会以某个角度旋转。在这个例子中是45度。我尝试设置边界和其他东西..没有帮助。

我该怎么做? :/


图像从左下角到右上角的长度是否超过屏幕宽度或高度?如果是这种情况,我认为您无法旋转图像。 - ahodder
不,实际上它是一个10x150维度的图像。 - Tzanter
3个回答

17

你可以使用 setRotation(int) 方法来旋转一个 ImageView。

// rotate imageView 45 around center pivot point
imageView.setPivotX(imageView.getWidth()/2);
imageView.setPivotY(imageView.getHeight()/2);
imageView.setRotation(45);

参考资料:http://goo.gl/WhhGM 编辑:由于URL中含有右括号,必须将链接缩短,否则某些浏览器可能无法打开。


这是针对API版本大于等于11的,但我想这对我也有效。无论如何,谢谢,我会把它标记为答案。 - Tzanter
我在一个按钮中使用了这段代码。第一次单击可以完美运行,但是在后续的单击中不再旋转。我应该添加其他代码来解决这个问题吗? - Eggakin Baconwalker
1
@user2751628 多次运行此代码不会有任何作用。setRotation 不会增加旋转,它将其设置为 45,您需要执行类似于 imageView.setRotation(imageView.getRotation()); 的操作。 - Spencer

0
这是我在我的应用程序中使用view.setRotation(float angle)的方法,希望对你有所帮助:
//to make rotation use next code
imageView.setPivotX(imageView.getWidth() / 2);
imageView.setPivotY(imageView.getHeight() / 2);
imageView.setRotation(45);

//to reset rotate state to initial position    
imageView.setPivotX(imageView.getWidth() / 2);
imageView.setPivotY(imageView.getHeight() / 2);    
imageView.setRotation(0);

基于Spencer的回答


-1

这个函数对我来说可行。

public static Bitmap rotateImage (Bitmap srcBitmap, int width, int height, int rotation)
    {
        // create rotated image
        Matrix matrix = new Matrix();
        rotation =  (rotation +1 )   % 3;
        rotation = rotation * 90;
        matrix.postRotate( rotation,
                width,
                height );
        Bitmap rotatedBmp = Bitmap.createBitmap( srcBitmap,
                0,
                0,
                srcBitmap.getWidth(),
                srcBitmap.getHeight(),
                matrix,
                false );

        return rotatedBmp;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接