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

137 阅读2分钟

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

函数

sharedTransition(String, SharedTransitionOptions)

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

设置共享元素转场。

说明

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

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

自定义类型说明

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 类型的对象。

参数名参数类型必填默认值描述
durationInt321000描述共享元素转场动效播放时长。单位:毫秒。
curveCurveCurve.Linear动画曲线。
delayInt320延迟播放时间。单位:毫秒。
motionPathMotionPathOptions-运动路径信息。
zIndexInt32-设置Z轴。
typeSharedTransitionEffectTypeSharedTransitionEffectType.Exchange动画类型。

MotionPathOptions

init(String, Float64, Float64, Bool)

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

创建一个 MotionPathOptions 类型的对象。

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

示例

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

// 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