针绕其指针头旋转

时间:2015-04-24 22:27:42

标签: android animation rotation

enter image description here我有一个针图像,当给定的值发生变化时我需要旋转。获得的值是随机的。

我在xml中创建了一个imageview图像。

      <RelativeLayout
    android:id="@+id/relativeLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerInParent="false" >

    <ImageView
        android:id="@+id/meter_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:layout_marginTop="54dp"
        android:src="@drawable/gauge_meter" />

    <ImageView
        android:id="@+id/meter_needle_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/meter_image"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="14dp"
        android:src="@drawable/meter_needle" />
</RelativeLayout>

我使用以下代码进行了旋转,但之后它不是在底部轴旋转

 RotateAnimation rpmNeedleDeflection = new RotateAnimation((float) (0.5f), (float) (90), 130, 0);

     rpmNeedleDeflection.setDuration(500);

     rpmNeedleDeflection.setFillAfter(true);

     rpmArrowView.startAnimation(rpmNeedleDeflection);

我仍然在弄清楚旋转是如何工作的,在我的情况下,我需要根据速度设置角度。但是现在给出了一个值,我如何让它从针的底部和绕轴旋转?

编辑:针头为31 * 113,底部图像为224 * 224

2 个答案:

答案 0 :(得分:4)

要解决此问题,您有两个选择:

选项1:

将针图像的大小调整为与背景图像完全相同的大小,即从31乘113到224乘224.执行此操作时,请确保您实际上并未将图像缩放到此大小(这将导致奇怪的拉伸针图像)。你想要做的是创建一个透明的图像224x224,并将原始尺寸(31x113)的针图像复制粘贴到这个新的透明图像中,这样针的基圆正好在224x224的中心。透明图像,并与&#34;虚构&#34;正确对齐背景。保存并将图像导出为png格式,并将此图像用作针图像。

现在您需要做的就是确保2张图像完全对齐。这不应该是困难的,因为它们应该都是相同的尺寸。旋转针图像时,您将获得所需的结果。

选项2:

我们假设您无法调整图片大小 - 可能是因为它被您的程序的其他部分使用,或者其他原因。您的第二个选择是定位图像,并使用轴点确保它通过代码正确定位。

要做到这一点,您需要水平居中图像,并且要垂直地对齐图像,以便针的基部直接位于背景的中心。< / p>

就定位而言,需要一些尝试和错误才能使其完美,但似乎你已经将这部分钉入了。你缺少的是转动的枢轴点。让我们看看我们如何计算它:

数学时间!

我猜测直径等于图像的宽度,因为它是最宽的部分。这意味着针的水平中心位于图像宽度的一半处:

final int pivotX = rpmArrowView.getMeasuredWidth() / 2;

图像的垂直中心应该相同,但图像的底部除外:

final int pivotY = rpmArrowView.getMeasuredHeight() - rpmArrowView.getMeasuredWidth() / 2;

现在,在制作动画之前,请务必设置轴心点:

rpmArrowView.setPivotX(pivotX);
rpmArrowView.setPivotY(pivotY);

然后动画:

rpmArrowView.animate().rotation(someDegree).setDuration(someDuration)

那就是它!它可能需要更多的调整来使定位完美,但这是它的要点。

希望其中一个选项可以帮助你。

答案 1 :(得分:1)

您只需使针图像与底部图像的尺寸相同,将两者都居中。您必须在中心创建另一个224 * 224透明图像,然后旋转应该很容易与中心匹配。 然后,使用以下Rotation Constructor就足够了:

RotateAnimation(float fromDegrees, float toDegrees)
相关问题