鸿蒙5.0开发进阶:ArkTS组件-属性动画 (animation)

往期鸿蒙5.0全套实战文章必看:(文中附带全栈鸿蒙5.0学习资料)


属性动画 (animation)

组件的某些通用属性变化时,可以通过属性动画实现渐变过渡效果,提升用户体验。支持的属性包括widthheightbackgroundColoropacityscalerotatetranslate等。布局类改变宽高的动画,内容都是直接到终点状态,例如文字、Canvas的内容等,如果要内容跟随宽高变化,可以使用renderFit属性配置。

说明

从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。

卡片能力: 从API version 9开始,该接口支持在ArkTS卡片中使用。

接口

animation(value:AnimateParam)

元服务API: 从API version 11开始,该接口支持在元服务中使用。

参数:

参数类型是否必填描述
valueAnimateParam设置动画效果相关参数。

属性动画只对写在animation前面的属性生效,且对组件构造器的属性不生效。

@State widthSize: number = 250;
@State heightSize: number = 100;
@State rotateAngle: number = 0;
@State flag: boolean = true;
@State space: number = 10;
// ...
Column({ space: this.space }) // 改变Column构造器中的space动画不生效
 .onClick(() => {
   if (this.flag) {
     this.widthSize = 150;
     this.heightSize = 60;
     this.space = 20; // 改变this.space动画不生效
   } else {
     this.widthSize = 250;
     this.heightSize = 100;;
     this.space = 10; // 改变this.space动画不生效
   }
   this.flag = !this.flag;
 })
 .margin(30)
 .width(this.widthSize) // 只有写在animation前面才生效
 .height(this.heightSize) // 只有写在animation前面才生效
 .animation({
   duration: 2000,
   curve: Curve.EaseOut,
   iterations: 3,
   playMode: PlayMode.Normal
 })
 // .width(this.widthSize) // 动画不生效
 // .height(this.heightSize) // 动画不生效

示例

该示例通过animation实现了组件的属性动画。

// xxx.ets
@Entry
@Component
struct AttrAnimationExample {
  @State widthSize: number = 250
  @State heightSize: number = 100
  @State rotateAngle: number = 0
  @State flag: boolean = true

  build() {
    Column() {
      Button('change size')
        .onClick(() => {
          if (this.flag) {
            this.widthSize = 150
            this.heightSize = 60
          } else {
            this.widthSize = 250
            this.heightSize = 100
          }
          this.flag = !this.flag
        })
        .margin(30)
        .width(this.widthSize)
        .height(this.heightSize)
        .animation({
          duration: 2000,
          curve: Curve.EaseOut,
          iterations: 3,
          playMode: PlayMode.Normal
        })
      Button('change rotate angle')
        .onClick(() => {
          this.rotateAngle = 90
        })
        .margin(50)
        .rotate({ angle: this.rotateAngle })
        .animation({
          duration: 1200,
          curve: Curve.Friction,
          delay: 500,
          iterations: -1, // 设置-1表示动画无限循环
          playMode: PlayMode.Alternate,
          expectedFrameRateRange: {
            min: 20,
            max: 120,
            expected: 90,
          }
        })
    }.width('100%').margin({ top: 20 })
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值