@IT·互联网鸿蒙(HarmonyOS)开发知识

[OpenHarmony UI实战]自定义对话框动效

2024-09-11  本文已影响0人  迪士尼在逃程序员

前言

安卓可以通过 setWindowAnimations 方法可以设置自定义对话框进入时的各种动效,项目中要求模拟滑入动效;本文以下图实现效果(点击按钮后从上方飞入一个模态对话框)的实现代码为例提供一种思路和方法

实现思路和方法

模态对话框自带动效

OpenHarmony 提供了 自定义弹窗 ,模态对话框通常可以采用弹窗实现。

自定义弹窗组件在 api10 新增了 openAnimation 参数,类型为 AnimateParam,可以设置自定义设置弹窗弹出的动画效果相关参数;但 AnimateParam 只能设置动画时间,不能设置滑入动效;无法直接达成所需目标效果

组件间转场动效

OpenHarmony 系统的转场动画效果丰富;如组件内转场主要通过 transition 属性配置转场参数,在组件插入和删除时显示过渡动效;支持透明度/平移/旋转等动效且可以多种动效组合显示;图中所示动效可以通过 move 实现

思路及代码实现

由此可以结合上述技术点实现丰富动效:

1、定义一个变量 visible 控制弹窗内内容插入或删除

2、弹窗自定义 openAnimation,在 onFinish 回调中设置 visible 插入弹窗内容

3、弹窗中定义动画效果

具体代码如下,api10 上可以直接运行

// xxx.ets
@CustomDialog
struct CustomDialogExample {
  controller: CustomDialogController

  @Link visible:boolean

  build() {
    if (this.visible) {
      Column() {
        Text('Change text').fontSize(20).margin({ top: 10, bottom: 10 })
        TextInput({ placeholder: '' }).height(60).width('90%')
          .onChange((value: string) => {

          })
        Text('Whether to change a text?').fontSize(16).margin({ bottom: 10 })
      }.borderRadius(10)
      .backgroundColor(Color.White)
      .transition(TransitionEffect.move(TransitionEdge.TOP).animation({ duration: 1000}))
      //.transition(TransitionEffect.move(TransitionEdge.TOP).animation({ duration: 1000}).combine(TransitionEffect.rotate({ z: 1, angle: 180 })))
    }
  }

  aboutToDisappear() {
    this.visible = false
  }
}

@Entry
@Component
struct CustomDialogUser {
  @State inputValue: string = 'click me'
  @State visible:boolean = false

  dialogController: CustomDialogController | null = new CustomDialogController({
    builder: CustomDialogExample({
      visible: $visible
    }),
    autoCancel: true,
    alignment: DialogAlignment.Bottom,
    offset: { dx: 0, dy: -20 },
    gridCount: 4,
    customStyle: true,
    backgroundColor: 0xd9ffffff,
    cornerRadius: 10,
    openAnimation:{duration:0, onFinish:()=>{
      this.visible = true
    }},
  })

  build() {
    Column() {
      Button(this.inputValue)
        .onClick(() => {
          if (this.dialogController != null) {
            this.dialogController.open()
          }
        }).backgroundColor(0x317aff)
    }.width('100%').margin({ top: 5 })
  }
}

写在最后

如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙

上一篇 下一篇

猜你喜欢

热点阅读