• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# ArkTS卡片为组件添加动效
2
3
4ArkTS卡片开放了使用动画效果的能力,支持[显式动画](../reference/apis-arkui/arkui-ts/ts-explicit-animation.md)、[属性动画](../reference/apis-arkui/arkui-ts/ts-animatorproperty.md)、[组件内转场](../reference/apis-arkui/arkui-ts/ts-transition-animation-component.md)能力。需要注意的是,ArkTS卡片使用动画效果时具有以下限制:
5
6**表1** 动效参数限制
7
8| 名称 | 参数说明 | 限制描述 |
9| -------- | -------- | -------- |
10| duration | 动画播放时长 | 限制最长的动效播放时长为1秒,当设置大于1秒的时间时,动效时长仍为1秒。 |
11| tempo | 动画播放速度 | 卡片中禁止设置此参数,使用默认值1。 |
12| delay | 动画延迟执行的时长 | 卡片中禁止设置此参数,使用默认值0。 |
13| iterations | 动画播放次数 | 卡片中禁止设置此参数,使用默认值1。 |
14
15>**说明:**
16>
17>静态卡片不支持使用动效能力。
18
19## 组件自身动效
20以下示例代码使用[animation](../reference/apis-arkui/arkui-ts/ts-animatorproperty.md)接口实现了按钮旋转的动画效果。
21
22![WidgetAnimation](figures/WidgetAnimation.gif)
23
24
25
26```ts
27// entry/src/main/ets/widget/pages/WidgetCard.ets
28@Entry
29@Component
30struct AnimationCard {
31  @State rotateAngle: number = 0;
32
33  build() {
34    Row() {
35      Button('change rotate angle')
36        .height('20%')
37        .width('90%')
38        .margin('5%')
39        .onClick(() => {
40          this.rotateAngle = (this.rotateAngle === 0 ? 90 : 0);
41        })
42        .rotate({ angle: this.rotateAngle })
43        .animation({
44          curve: Curve.EaseOut,
45          playMode: PlayMode.Normal,
46        })
47    }.height('100%').alignItems(VerticalAlign.Center)
48  }
49}
50```
51## 组件转场动效
52以下示例代码使用[transition](../reference/apis-arkui/arkui-ts/ts-transition-animation-component.md)接口实现了在卡片内图片出现与消失的动画效果。
53
54![WidgetAnimation](figures/WidgetTransitionAnimation.gif)
55
56```ts
57// entry/src/main/ets/widget/pages/WidgetCard.ets
58@Entry
59@Component
60struct TransitionEffectExample1 {
61  @State flag: boolean = true;
62  @State show: string = 'show';
63
64  build() {
65    Column() {
66      Button(this.show).width(80).height(30).margin(30)
67        .onClick(() => {
68          // 点击Button控制Image的显示和消失
69          if (this.flag) {
70            this.show = 'hide';
71          } else {
72            this.show = 'show';
73          }
74          this.flag = !this.flag;
75        })
76      if (this.flag) {
77        // Image的显示和消失配置为相同的过渡效果(出现和消失互为逆过程)
78        // 出现时从指定的透明度为0、绕z轴旋转180°的状态,变为默认的透明度为1、旋转角为0的状态,透明度与旋转动画时长都为1000ms
79        // 消失时从默认的透明度为1、旋转角为0的状态,变为指定的透明度为0、绕z轴旋转180°的状态,透明度与旋转动画时长都为1000ms
80        Image($r('app.media.testImg')).width(200).height(200)
81          .transition(TransitionEffect.OPACITY.animation({ duration: 1000, curve: Curve.Ease }).combine(
82            TransitionEffect.rotate({ z: 1, angle: 180 })
83          ))
84      }
85    }.width('100%')
86  }
87}
88```