华为仓颉鸿蒙HarmonyOS NEXT原生UI转场动画之共享元素转场 (sharedTransition)

当路由进行切换时,可以通过设置组件的 sharedTransition 属性将该元素标记为共享元素并设置对应的共享元素转场动效。

函数

sharedTransition(String, SharedTransitionOptions)

public func sharedTransition(id: String, options!: SharedTransitionOptions): This

设置共享元素转场。

说明

type为SharedTransitionEffectType.Exchange时motionPath才会生效。

参数名 参数类型 必填 默认值 描述
id String - 两个页面中id值相同且不为空字符串的组件即为共享元素,在页面转场时可显示共享元素转场动效。
options sharedTransitionOptions - 共享元素转场动画参数。

自定义类型说明

SharedTransitionOptions

init(Int32, Curve, Int32, MotionPathOptions, Int32, SharedTransitionEffectType)

public init(
        duration!: Int32 = 1000,
        curve!: Curve = Curve.Linear,
        delay!: Int32 = 0,
        motionPath!: MotionPathOptions = MotionPathOptions(),
        zIndex!: Int32 = 0,
        `type`!: SharedTransitionEffectType = SharedTransitionEffectType.SharedEffectExchange
    )

创建一个 sharedTransitionOptions 类型的对象。

参数名 参数类型 必填 默认值 描述
duration Int32 1000 描述共享元素转场动效播放时长。单位:毫秒。
curve Curve Curve.Linear 动画曲线。
delay Int32 0 延迟播放时间。单位:毫秒。
motionPath MotionPathOptions - 运动路径信息。
zIndex Int32 - 设置Z轴。
type SharedTransitionEffectType SharedTransitionEffectType.Exchange 动画类型。

MotionPathOptions

init(String, Float64, Float64, Bool)

public init(
        path!: String ="",
        `from`!: Float64 = 0.0,
        to!: Float64 = 1.0,
        rotatable!: Bool = false
    )

创建一个 MotionPathOptions 类型的对象。

参数名 参数类型 必填 默认值 描述
path String - 位移动画的运动路径,使用svg路径字符串。设置为空字符串时相当于不设置路径动画。
from Float64 0.0 运动路径的起点。取值范围:[0, 1]设置小于0或大于1的值时,按默认值0处理。
to Float64 1.0 运动路径的终点。取值范围:[0, 1]设置小于0或大于1的值时,按默认值1处理,且满足to值 >= 异常值处理后的from值。
rotatable Bool false 是否跟随路径进行旋转。

示例

示例代码为点击图片跳转页面时,显示共享元素图片的自定义转场动效。

// index.cj
    @Entry
    @Component
    class MyView {
        @State var active: Bool = false
        func build() {
            Column() {
       Image(@r(app.media.startIcon)).width(50).height(50).onClick {
                    e => Router.push(url: "Page1")
                }.sharedTransition("sharedImage",
                    options: SharedTransitionOptions(duration: 800, curve: Curve.Linear, delay: 100))
            }
        }
    }
    // PageB.cj
    @Entry
    @Component
    class PageBMyView {
        func build() {
            Stack() {
       Image(@r(app.media.startIcon))
        .width(150)
        .height(150)
        .sharedTransition(
         "sharedImage",
         options: SharedTransitionOptions(duration: 800, curve: Curve.Linear, delay: 100)
                    )
            }.width(100.percent).height(100.percent)
        }
    }

如对您有帮助,帮忙点个“在看 、关注” 让更多的人受益~!

技术交流群可加wx“LB-9191”备注cangjie

posted @ 2024-12-24 21:29  BisonLiu  阅读(44)  评论(0)    收藏  举报