二十一、组件内转场动画

发布时间 2024-01-03 09:46:42作者: 创客未来

1、if/else产生组件内转场动画

if/else语句可以控制组件的插入和删除。如下代码即可以通过Button的点击事件,控制if的条件是否满足,来控制if下的Image组件是否显示。

/**
 * author:创客未来
 * copyright:com.ckFuture.hrb
 * transition必须配合animateTo使用
 */
@Entry
@Component
struct IfElseTransition {
  @State flag: boolean = true
  build() {
    Column() {
      Button(this.flag?'隐藏':'显示').fontSize(30).margin(30).width(150).height(50)
        .onClick(() => {
          animateTo({}, () => {
            this.flag = !this.flag
          })
      })
      if(this.flag){
        Image($r('app.media.icon')).width(300)
        //   .transition({
        //   type:TransitionType.All,
        //   opacity:1
        // })
          //进场动画
          .transition({
            type:TransitionType.Insert,
            //插入的起始位置
            translate:{x:200,y:-200},
            opacity:0,
            rotate:{angle:360}
          })
          //出场动画
          .transition({
            type:TransitionType.Delete,
            //插入的起始位置
            translate:{x:200,y:-200},
            opacity:0,
            rotate:{angle:360}
          })
      }
    }
    .width('100%').height('100%')
  }
}

 

2、ForEarch产生组件内转场动画

和if/else类似,ForEarch可以通过控制数组中的元素个数,来控制组件的插入和删除。通过ForEarch来产生组件内转场动画,仍然需要两个条件。

ForEarch里的组件配置了transition效果。

在animateTo的闭包中控制组件的插入或删除,即控制数组的元素添加和删除。

以下代码事使用ForEarch产生组件内转场动画的一个示例:

@Entry
@Component
struct ForEarchTransition {
  @State poem: string[] = [
    '满堂花醉三千客,人生得意须尽欢。',
    '仰天大笑出门去,归来倚仗自叹息。',
    '天生我材必有用,会须一饮三百杯。',
    '最是人间留不住,千金散尽还复来。'
  ]

  build() {
    Column() {
      Column() {
        ForEach(this.poem,item=>{
          Text(item)
            .fet_text()
            .transition({
              type:TransitionType.All,
              translate:{x:200,y:100}
            })
        },item=>JSON.stringify(item))
      }

      Button('向头部添加元素').fet_btn(Color.Orange, () => {
        animateTo({}, () => {
          this.poem.unshift('芙蓉帐暖度春宵,朕与将军解战袍。')
        })
      })
      Button('向尾部添加元素').fet_btn(Color.Green, () => {
        animateTo({}, () => {
          this.poem.push('问世间情为何物,两岸猿声啼不住。')
        })
      })
      Button("删除头部元素").fet_btn(Color.Blue, () => {
        animateTo({}, () => {
          this.poem.shift()
        })
      })
      Button("删除尾部元素").fet_btn(Color.Red, () => {
        animateTo({}, () => {
          this.poem.pop()
        })
      })
    }
    .width('100%')
    .height('100%')
  }
}
@Extend(Text) function  fet_text(){
  .height(50)
  .backgroundColor(Color.Pink)
  .margin({top:5})
}
@Extend(Button) function fet_btn(bgColor:Color,click:Function){
  .width(200)
  .height(50)
  .margin({top:5})
  .fontSize(18)
  .backgroundColor(bgColor)
  .onClick(() => {
    //此处的click是一个形参,具体代表的是调用传递过来的函数,后方根据小括号代表执行传递来的函数。
      click()
  })
}