安卓如何以底部中心为旋转点旋转图像?

6
请在标记重复或关闭问题之前仔细阅读整个问题。
我想要围绕基础中心点旋转图像(具体来说是箭头图片)。
例如,开始时我的图像就像时钟上的秒针在9点。 假设我将该图像旋转30度,则应该看起来像时钟秒针在10处,如果旋转120度,则为1处的时钟秒针。
因此,我想要将该图像围绕其基础的中心(沿x轴)旋转。
如果我首先编写代码,则应该将什么作为枢轴(X和Y)?
imageView.setPivotX(1f);
            imageView.setPivotY(1f);
            imageView.setRotation(-30);

或者第二个代码

Matrix matrix = new Matrix();
    imageView.setScaleType(ScaleType.MATRIX);
    matrix.postRotate((float) 20, 0f, 0f);
    imageView.setImageMatrix(matrix);

或第三方代码

Bitmap myImg = BitmapFactory.decodeResource(getResources(), R.drawable.arrow_0_degree);
    Matrix matrix = new Matrix();
    matrix.postRotate(30);
    Bitmap rotated = Bitmap.createBitmap(myImg, 0, 1, myImg.getWidth(), myImg.getHeight(), matrix, true);
    imageView.setImageBitmap(rotated);

或者第四段代码。
final RotateAnimation rotateAnim = new RotateAnimation(0.0f, degree,
        RotateAnimation.RELATIVE_TO_SELF, 0.5f,
        RotateAnimation.RELATIVE_TO_SELF, 0.5f);

rotateAnim.setDuration(0);
rotateAnim.setFillAfter(true);
imgview.startAnimation(rotateAnim);

为了更好地理解,添加了一张图像,该图像顺时针旋转了90度。

希望未来Google能够添加更多和更清晰的关于枢轴点的文档。

提前致谢。enter image description here

2个回答

12

你几乎用了正确的第四段代码 ^^

你可以像这样实现:

    final RotateAnimation rotateAnim = new RotateAnimation(0.0f, 30,
            RotateAnimation.RELATIVE_TO_SELF, 0.5f,
            RotateAnimation.RELATIVE_TO_SELF, 1f);
    rotateAnim.setDuration(0);
    rotateAnim.setFillAfter(true);
    mImageView.setAnimation(rotateAnim);
    rotateAnim.start();

setFillAfter (true) 有什么作用? - IgorGanapolsky
3
动画结束时,视图停留在动画结束的位置。 - koni
我尝试了这段代码,但不幸的是它对我不起作用。你能否建议一下为什么它不起作用? - Maya Mohite

0

您可以通过将pivotX设置为箭头宽度,将pivotY设置为箭头高度/2,然后进行旋转来简单地旋转箭头。请参考以下代码:

            <ImageView
                android:id="@+id/imgVwArrow"
                android:layout_width="128dp"
                android:layout_height="36dp"
                android:transformPivotX="128dp"
                android:transformPivotY="18dp"
                android:src="@mipmap/ic_arrow" />

这里宽度为128dp,pivotX也是如此,高度为36dp,而pivotY为18dp。现在您可以直接在xml中设置旋转,或使用以下代码进行编程设置:

imgVwArrow.rotation = 30f

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