我如何使用'RotateDrawable'?

Ker*_*rry 17 android android-drawable

任何人都可以告诉我他们是如何使用'RotateDrawable'来处理它是来自代码还是XML或两者兼而有之?关于Drawables动画的文档非常糟糕,动画似乎只适用于图像.我希望能够为所有drawables制作动画.当我试图从XML获取RotateDrawble时只会导致异常.从XML中查找RotateDrawable的正确功能是什么?

非常感谢

Kerubu

Mar*_*ton 10

您必须为"level"属性设置动画,其中0是起始值,10000是结束值.

以下示例从开始到结束动画,您可以使用此方法轻松地反转动画.

final RotateDrawable rotateDrawable = ...
ObjectAnimator.ofInt(rotateDrawable, "level", 0, 10000).start();
Run Code Online (Sandbox Code Playgroud)


mar*_*inj 6

我想在 ImageView 上添加一个动画进度图标的完整示例,它基于 Mark Hetherington 的回答。

所以我的动画如下所示:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
                 android:pivotX="50%"
                 android:pivotY="50%"
                 android:fromDegrees="0"
                 android:toDegrees="-360"
                 android:duration="100"
                 android:drawable="@drawable/ic_loop_black_24dp"
    />
Run Code Online (Sandbox Code Playgroud)

图标来自https://material.io/icons/

那么我的布局包含一个 ImageView 如下:

        <ImageView
            android:id="@+id/progress"
            android:layout_marginTop="0dp"
            android:layout_marginLeft="-3dp"
            android:layout_width="30dp"
            android:layout_height="30dp"

            android:visibility="gone"
            android:scaleType="fitCenter"
            android:background="@drawable/progress_anim"
            android:layout_gravity="center_horizontal|center_vertical"
            />
Run Code Online (Sandbox Code Playgroud)

最后在我需要显示动画时的代码中:

    RotateDrawable rotateDrawable = ((RotateDrawable)progressImage.getBackground());
    ObjectAnimator anim = ObjectAnimator.ofInt(rotateDrawable, "level", 0, 10000);
    anim.setDuration(1000);
    anim.setRepeatCount(ValueAnimator.INFINITE);
    anim.start();
Run Code Online (Sandbox Code Playgroud)


Dav*_*unt 2

我没有使用过 RotateDrawable,但如果您只是想在图形上设置旋转动画,则不需要它。像 RotateDrawable 这样具有“级别”的 Drawable 旨在传达信息而不是动画视图。

以下代码围绕其中心旋转 ImageView:

ImageView myImageView = (ImageView)findViewById(R.id.my_imageview);

AnimationSet animSet = new AnimationSet(true);
animSet.setInterpolator(new DecelerateInterpolator());
animSet.setFillAfter(true);
animSet.setFillEnabled(true);

final RotateAnimation animRotate = new RotateAnimation(0.0f, -90.0f,
    RotateAnimation.RELATIVE_TO_SELF, 0.5f, 
    RotateAnimation.RELATIVE_TO_SELF, 0.5f);

animRotate.setDuration(1500);
animRotate.setFillAfter(true);
animSet.addAnimation(animRotate);

myImageView.startAnimation(animSet);
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的回复大卫。如果我正确理解你的方法,这会旋转整个视图,而我最终希望能够旋转/动画视图中的单个可绘制对象,例如指针在固定的背景上旋转,因为它是表盘的刻度。这就是为什么我尝试使用 RotateDrawable 但不幸的是无法理解文档! (3认同)