如何从不同角度旋转视图?

时间:2015-11-02 08:57:02

标签: android boolean android-animation screen-orientation android-orientation

我正在尝试将ImageButton旋转180度,以便与反向纵向方向匹配。当我以与其他方向相同的方式改变时,结果是完美的,但不是动画。

 public void onOrientationChanged(int DeviceAngle) {
      float MyButtonCurrentAngle = MyButton.getRotation(); //Gets portrait rotation (0)
           if(DeviceAngle > 350 || DeviceAngle < 10) { //Portrait
                MyButton.animate().rotationBy(- MyButtonCurrentAngle).setDuration(100).start();
           } else if(DeviceAngle > 80 && DeviceAngle < 100) { //Reverse Landscape
                MyButton.animate().rotationBy(-90 - MyButtonCurrentAngle ).setDuration(100).start();
            } else if(DeviceAngle > 170 && DeviceAngle < 190) { //Reverse Portrait
                MyButton.animate().rotationBy(180 -  MyButtonCurrentAngle).setDuration(100).start();
           } else if(DeviceAngle > 260 && DeviceAngle < 280) { //Landscape
                MyButton.animate().rotationBy(90 - MyButtonCurrentAngle ).setDuration(100).start();
           }          

我认为会发生这种情况,因为浮动MyButtonCurrentAngle从DeviceAngle获取的MyButton旋转角度值(0或未旋转)在350和10(0或360,纵向方向)之间,并将其用作参考。

尽管我仍然怀疑,但我放弃了之前的案例。浮动似乎与其他方向很好地协作,我认为问题是反向纵向方向的动画。该按钮不应旋转180度,而应旋转90度或-90度。这是因为您无法通过任何横向选项将设备从纵向旋转到反转纵向。 (无法直接将人像旋转到反转人像。)

经过多次不成功的尝试后,我得出的结论是,在旋转按钮并检测到方向为横向或反向横向后,我无法使用MyButton获取角度值。我想到了另一个浮点数的创建,以获得反转肖像MyButton角度值,但是此活动的方向设置为纵向,所以这没有意义。

因此,我需要在使用浮点旋转之后获取MyButton旋转角度,使用此值作为循环条件,并根据结果,在两个不同的动画中将其旋转90度或-90度。这是我对此问题的最新解决方法:

    while (MyButtonCurrentAngle==90) { 
    if (DeviceAngle > 170 && DeviceAngle < 190) {
        MyButton.animate().rotationBy(90 - MyButtonCurrentAngle).setDuration(100).start();
    }
}
while (MyButtonCurrentAngle==270) { 
    if (DeviceAngle > 170 && DeviceAngle < 190) {
        MyButton.animate().rotationBy(-90 - MyButtonCurrentAngle).setDuration(100).start();
    }
}

基本上,它处理从横向和反向横向到反向纵向的设备方向。这没有触发任何动画,所以MyButtonCurrentAngle浮动角度值从未改变或无法检测到? if语句为何不能读取它?我不知道,我想知道我做错了什么。提前谢谢。

2 个答案:

答案 0 :(得分:1)

解决方案:

Continent

答案 1 :(得分:0)

如果您发现此代码正在运行(通过断点调试或Logcat语句),请尝试在UI线程上运行动画。

YourActivity.runOnUiThread(new Runnable() {
    public void run() 
        MyButton.animate().rotationBy(90 - MyButtonCurrentAngle).setDuration(100).start();
    }
});

您可能还需要调用start。