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

11

我该如何实现将一个图标转换成另一个图标的动画效果,比如汉堡包变成箭头(导航抽屉)或者铅笔变成叉号(收件箱)?我该如何实现这种动画效果?

2个回答

16
图标动画可以使用animated-vector实现。
首先将图标定义为矢量可绘制对象。例如,让我们采用在这里找到的勾叉动画。我们将把ic_tick动画到ic_crossic_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>

在如何在可绘制矢量之间进行动画处理方面,有一些限制,但如果您清楚地了解要将什么内容进行动画处理,以及动画应该如何执行,则可以以某种方式进行黑客攻击。


有没有办法从图像文件自动获取图标矢量 XML 文件(ic_cross.xml 或 ic_tick.xml)? - user5457243
1
@Caketray 有几个工具可以将png转换为svg(矢量xml),只需进行谷歌搜索即可。 - kushpf
我可以控制动画吗?比如说,如果我有一个滚动条,当我滚动滚动条时,图标应该从一个转换为另一个,如果我停止滚动,则转换不应继续。基本上,我想要控制转换。 - Sujith Niraikulathan
使用.png图像是否可行? - Akash Patel

9

哇,太酷了,谢谢你! - Dio Lantief Widoyoko
@DioLantiefWidoyoko,我们非常欢迎你。 - Aminul Haque Aome

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接