首页 > 解决方案 > 在android中旋转图像中心而不是宽圆圈

问题描述

我有一个 ImageView 和 Button。按钮视图位于屏幕底部。ImageView 位于按钮上方。当我单击按钮时,图像应移动到屏幕中心。移动到中心后,单击图像应该旋转。但在我的情况下,它以更宽的圆圈旋转,而不是在中心旋转。

我正在使用下面的代码。

            <ImageView
            android:id="@+id/image"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:scaleType="centerCrop"
            android:visibility="visible" />

            <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:text="Start" />

点击按钮后,移动到屏幕中心

image.animate().y(metrics.heightPixels / 2 - image.getHeight() / 2).x(metrics.widthPixels / 2 - image.getWidth() / 2)

在上述步骤之后旋转图像。

                RotateAnimation animRotate = new RotateAnimation(0.0f, 360.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            animRotate.setDuration(duration);
            animRotate.setInterpolator(new DecelerateInterpolator(1.5f));
image.startAnimation(animRotate)

它不是在中心旋转,而是像更宽的圆圈一样旋转。你能帮我吗。

标签: javaandroidandroid-layoutanimation

解决方案


视图的翻译发生在布局后。结果是,尽管视图出现在新位置(翻译后位置),但旋转动画仍然认为视图处于其原始位置(其布局位置)。您看到视图以大圆圈旋转,因为旋转中心是视图的预平移中心。为什么这对我来说是一个永恒的谜。

为了解决这个问题,您需要计算屏幕上显示的视图的真实中心。以下代码显示了如何做到这一点。视图从屏幕中心平移到左上角并原地旋转。(您不必使用全局布局侦听器。)

// Wait until everything is laid out before we can manipulate it.
image.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    int duration = 1000;
    @Override
    public void onGlobalLayout() {
        image.getViewTreeObserver().removeOnGlobalLayoutListener(this);

        // Save the initial location of the top-left corner of the view.
        float initX = image.getX();
        float initY = image.getY();
        image.animate().y(0).x(0).setDuration(duration).withEndAction(new Runnable() {
            @Override
            public void run() {
                // The post-translation center of the view is at the new top-left corner
                // plus 1/2 the width and height of the view. We need to compute the 
                // displacement from the original center to feed into the RotationAnimation.
                RotateAnimation animRotate =
                        new RotateAnimation(0.0f, 360.0f,
                                Animation.ABSOLUTE, image.getX() - initX + (image.getWidth() / 2f),
                                Animation.ABSOLUTE, image.getY() - initY + (image.getHeight() / 2f));
                animRotate.setDuration(duration);
                image.startAnimation(animRotate);
            }
        });

    }
});

在此处输入图像描述


推荐阅读