Android 将图标转换为另一个图标

Android transform icon into another one

我怎样才能实现将一个图标转换为另一个图标的动画效果,例如将汉堡转换为箭头(导航抽屉)或将铅笔转换为十字(收件箱)?如何存档此动画?

图标动画可以使用animated-vector实现

首先将您的图标定义为矢量绘图。例如,让我们拿一个 tick 来交叉动画,找到 here。我们将 ic_tick 动画化为 ic_cross

ic_cross.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="120dp"
        android:height="120dp"
        android:viewportWidth="@integer/viewport_width"
        android:viewportHeight="@integer/viewport_height">

    <group
        android:name="@string/groupTickCross"
        android:pivotX="@integer/viewport_center_x"
        android:pivotY="@integer/viewport_center_y">

        <path
            android:name="@string/cross"
            android:pathData="M6.4,6.4 L17.6,17.6 M6.4,17.6 L17.6,6.4"
            android:strokeWidth="@integer/stroke_width"
            android:strokeLineCap="square"
            android:strokeColor="@color/stroke_color"/>

    </group>

</vector>

ic_tick.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="120dp"
        android:height="120dp"
        android:viewportWidth="@integer/viewport_width"
        android:viewportHeight="@integer/viewport_height">

    <group
        android:name="@string/groupTickCross"
        android:pivotX="@integer/viewport_center_x"
        android:pivotY="@integer/viewport_center_y">

        <path
            android:name="@string/tick"
            android:pathData="M4.8,13.4 L9,17.6 M10.4,16.2 L19.6,7"
            android:strokeWidth="@integer/stroke_width"
            android:strokeLineCap="square"
            android:strokeColor="@color/stroke_color"/>

    </group>

</vector>

接下来我们为每个步骤创建动画师。 valueFrom 表示动画的起点,valueTo 是动画的最终产物。 interpolator 是插值类型,您可以在 Android 文档中找到更多信息。 duration 指定动画的持续时间。

tick_to_cross.xml

<objectAnimator
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:propertyName="pathData"
    android:valueFrom="M4.8,13.4 L9,17.6 M10.4,16.2 L19.6,7"
    android:valueTo="M6.4,6.4 L17.6,17.6 M6.4,17.6 L17.6,6.4"
    android:duration="@integer/duration"
    android:interpolator="@android:interpolator/fast_out_slow_in"
    android:valueType="pathType"/>

现在,我们使用 animated-vector 为矢量设置动画。这里 <target android:name 指定动画必须在其上完成的目标,而 android:animation 告诉动画要完成。

avd_tick_to_cross.xml

<animated-vector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/ic_tick">

    <target
        android:name="@string/tick"
        android:animation="@animator/tick_to_cross" />

</animated-vector>

对于如何在可绘制矢量之间设置动画有一些限制,但如果您清楚地了解要为什么设置动画以及动画应该如何进行,则可以通过某种方式破解它们。

你可以用ShapeShifter created by Alex Lockwood to transform icon to another. You can read this medium post and this YouTube video对ShapeShifter有个清晰的概念