关于android:ConstraintLayout20之MotionEffect简单的代码实现炫酷的动效

7次阅读

共计 2422 个字符,预计需要花费 7 分钟才能阅读完成。

MotionEffect

MotionEffect 是 2.1 中的一个新的 MotionHelper,能够让你依据视图的整体静止方向,主动为其援用的视图增加关键帧。它能够简化很多过渡动画的创作。

为了更好地了解它的作用,请看上面的例子。这个例子只应用了 MotionLayout 的 start 和 end 性能,它主动创立了两种场景下的过渡成果。

默认的两种状态之间的过渡做了一个线性插值的挪动成果——这个展现后果是凌乱的,并不令人欢快。

如果咱们看这个例子,咱们能够辨认出只向西挪动的元素(2、3、6、9),而其余元素则以其它不同的模式挪动(1、4、5、7、8)。

咱们能够应用 MotionEffect 对这些元素利用淡入淡出的成果,给人带来更愉悦的成果。

能够查看上面的 demo。

<androidx.constraintlayout.motion.widget.MotionLayout ... >
    <TextView android:id="@+id/t1" ... />
    <TextView android:id="@+id/t2" ... />
    <TextView android:id="@+id/t3" ... />
    <TextView android:id="@+id/t4" ... />
    <TextView android:id="@+id/t5" ... />
    <TextView android:id="@+id/t6" ... />
    <TextView android:id="@+id/t7" ... />
    <TextView android:id="@+id/t8" ... />
    <TextView android:id="@+id/t9" ... />

    ...

    <androidx.constraintlayout.helper.widget.MotionEffect
        android:id="@+id/fade"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:constraint_referenced_ids="t1,t2,t3,t4,t5,t6,t7,t8,t9"
    />
</androidx.constraintlayout.motion.widget.MotionLayout>

Controling which views get the effect

首先,只有 MotionEffect 中援用的视图才有可能失去成果。

其次,默认状况下,咱们会主动计算这些视图的次要挪动方向(在北、南、东、西之间),只有与该方向相同挪动的视图才会失去利用于它们的成果。

应用 motionEffect_move=auto|north|south|east|west,你能够笼罩它来指定你想要成果利用到哪个方向。

你也能够应用 motionEffect_strict=true|false 来让这个成果严格地利用于(或不利用于)做这个静止的元素。

默认成果 默认状况下,成果将利用淡出 / 淡入;你能够通过以下属性管制 alpha 的数量以及成果的开始 / 完结。

app:motionEffect_start="keyframe"
app:motionEffect_end="keyframe"

你也能够管制 alpha 和 translation 的数值。

app:motionEffect_alpha="alpha"
app:motionEffect_translationX="dimension"
app:motionEffect_translationX="dimension"

Custom effect

你也能够援用一个 ViewTransition 来代替默认的淡入淡出成果利用到 widget 上,只需设置 motionEffect_viewTransition,你就能够无限度地管制你想要利用的成果类型。

例如,要失去以下动画。

你能够创立一个 ViewTransition,并在 MotionEffect 中援用它。

在 layout xml 中:

<androidx.constraintlayout.helper.widget.MotionEffect
...
app:motionEffect_viewTransition="@+id/coolFade"/>

在 motion scene 中:

<ViewTransition android:id="@+id/coolFade">
    <KeyFrameSet>
        <KeyAttribute
            motion:framePosition="20"
            android:scaleX="0.1"
            android:scaleY="0.1"
            android:rotation="-90"
            android:alpha="0" />
        <KeyAttribute
            motion:framePosition="80"
            android:scaleX="0.1"
            android:scaleY="0.1"
            android:rotation="-90"
            android:alpha="0" />
    </KeyFrameSet>
</ViewTransition>

文末

您的点赞珍藏就是对我最大的激励!
欢送关注我,分享 Android 干货,交换 Android 技术。
对文章有何见解,或者有何技术问题,欢送在评论区一起留言探讨!

正文完
 0