【问题标题】:Rotating ImageView with RotateAnimation flickers between degree positions (Android)使用 RotateAnimation 旋转 ImageView 在度数位置之间闪烁(Android)
【发布时间】:2016-01-27 08:03:18
【问题描述】:

我在旋转 ImageView 并使其保持指向正确方向时遇到问题。本质上,ImageView 是一个箭头,它应该始终指向它所在的屏幕的边缘或角落(由陀螺仪的设备度数确定),但它只是在不正确的位置之间闪烁。例如,如果指针从屏幕的右上角开始并指向那个角,那么应该移动并指向屏幕的顶部,x-y 位置将正确移动,但指针在指向之间反弹左上角和右上角。

要设置指针的位置,我有这个:

public int pointerDegree = 0;
public void rotatePointerTo(int degree)
{
    if(degree==pointerDegree) //if it's already set to the degree it needs to be moved to
        return;
    final RotateAnimation rotate = new RotateAnimation(pointerDegree, degree,
            RotateAnimation.RELATIVE_TO_SELF, 0.5f,
            RotateAnimation.RELATIVE_TO_SELF, 0.5f);
    rotate.setInterpolator(new LinearInterpolator());
    rotate.setDuration(1);
    rotate.setFillEnabled(true);
    rotate.setFillAfter(true);
    pointer.startAnimation(rotate);
    pointerDegree = degree;
}

在 OnSensorChanged 函数中调用如下:

 int baseDegree = (int)degree%360;
    if(baseDegree > -5 && baseDegree < 5)
        rotatePointerTo(-90);
    else if(baseDegree >= 5 && baseDegree <= 85)
        rotatePointerTo(0);
    else if(baseDegree > 85 && baseDegree < 95)
        rotatePointerTo(45);
    else if(baseDegree >= 95 && baseDegree <= 175)
        rotatePointerTo(90);
    else if(baseDegree > 175 && baseDegree < 185)
        rotatePointerTo(135);
    else if(baseDegree >= 185 && baseDegree <= 265)
        rotatePointerTo(180);

我知道当我调用 rotatePointerTo() 时,我作为参数使用的度数可能不正确 - 我只是在尝试找出闪烁问题时用随机值填充它。

【问题讨论】:

  • 您是否尝试过使用调试器来识别传递给 OnSensorChanged 的​​值?
  • @OYRM 是的,这是我做的第一件事。很难说问题出在哪里,因为 OnSensorChanged 被调用了很多,并且每当它遇到断点时,它都被正确设置 - 当它动作不正确时基本上不可能捕捉到它,因为它运行得如此之快.
  • 有一种叫做去抖动的做法。设置保持记录和平均输入的逻辑,以便平均丢失高点和低点。如果愿意,您可以将其与调试相结合以找出异常值。原始传感器数据可以显示很多变化,数据处理可能会有所帮助。

标签: android imageview android-animation


【解决方案1】:

闪烁的问题可能在这一行:

rotate.setDuration(1);

这意味着您只需要 1 毫秒的时间为 View 设置动画,这非常非常短。

你的意思可能是:

rotate.setRepeatCount(1);

这意味着您正在播放一次动画。

我建议你看看这个类:ViewPropertyAnimator 它真的很简单直接,并且可以通过像这样旋转你的视图来为你节省很多 RotateAnimation 代码。 :

pointer.animate()
    .rotationBy(pointerDegree)
    .setInterpolator(new LinearInterpolator)
    .setDuration(100);

该类中有更多的rotationX和rotationY方法,一定要检查所有可用的方法。

【讨论】:

  • 非常感谢!我会全力以赴,让你知道进展如何。我知道可能有更好的方法来完成整个旋转,所以我一定会检查 ViewPropertyAnimator 类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-05
相关资源
最近更新 更多