• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.animator (动画)
2
3本模块提供组件动画效果,包括定义动画、启动动画和以相反的顺序播放动画等。
4
5> **说明:**
6>
7> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8>
9> 本模块从API version 9开始支持在ArkTS中使用。
10>
11> 该模块不支持在[UIAbility](../apis-ability-kit/js-apis-app-ability-uiAbility.md)的文件声明处使用,即不能在UIAbility的生命周期中调用,需要在创建组件实例后使用。
12>
13> 本模块功能依赖UI的执行上下文,不可在UI上下文不明确的地方使用,参见[UIContext](js-apis-arkui-UIContext.md#uicontext)说明。
14
15## 导入模块
16
17```ts
18import { Animator as animator, AnimatorOptions, AnimatorResult, SimpleAnimatorOptions } from '@kit.ArkUI';
19```
20
21## Animator
22
23定义Animator类。
24
25**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
26
27**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
28
29### create<sup>(deprecated)</sup>
30
31create(options: AnimatorOptions): AnimatorResult
32
33创建animator动画结果对象(AnimatorResult)。
34
35> **说明:**
36>
37> 从API version 9开始支持,从API version 18开始废弃,建议使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[createAnimator](js-apis-arkui-UIContext.md#createanimator)替代。
38>
39> 从API version 10开始,可以通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[createAnimator](js-apis-arkui-UIContext.md#createanimator)来明确UI的执行上下文。
40
41**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
42
43**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
44
45**参数:**
46
47| 参数名     | 类型                                  | 必填   | 说明      |
48| ------- | ----------------------------------- | ---- | ------- |
49| options | [AnimatorOptions](#animatoroptions) | 是    | 定义动画选项。 |
50
51**返回值:**
52
53| 类型                                | 说明            |
54| --------------------------------- | ------------- |
55| [AnimatorResult](#animatorresult) | Animator结果接口。 |
56
57**错误码**:
58
59以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
60
61| 错误码ID | 错误信息 |
62| ------- | -------- |
63| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
64
65**示例:**
66
67> **说明:**
68>
69> 推荐通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[createAnimator](js-apis-arkui-UIContext.md#createanimator)接口明确UI上下文。
70
71<!--deprecated_code_no_check-->
72```ts
73import { Animator as animator, AnimatorOptions } from '@kit.ArkUI';
74
75let options: AnimatorOptions = {
76  duration: 1500,
77  easing: "friction",
78  delay: 0,
79  fill: "forwards",
80  direction: "normal",
81  iterations: 3,
82  begin: 200.0,
83  end: 400.0
84};
85animator.create(options); // 建议使用 UIContext.createAnimator()接口
86```
87
88### create<sup>18+</sup>
89
90create(options: AnimatorOptions \| [SimpleAnimatorOptions](#simpleanimatoroptions18)): AnimatorResult
91
92创建animator动画结果对象(AnimatorResult)。与[create](#createdeprecated)相比,新增对[SimpleAnimatorOptions](#simpleanimatoroptions18)类型入参的支持。
93
94**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
95
96**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
97
98**参数:**
99
100| 参数名     | 类型                                  | 必填   | 说明      |
101| ------- | ----------------------------------- | ---- | ------- |
102| options | [AnimatorOptions](#animatoroptions) \| [SimpleAnimatorOptions](#simpleanimatoroptions18) | 是    | 定义动画参数选项。 |
103
104**返回值:**
105
106| 类型                                | 说明            |
107| --------------------------------- | ------------- |
108| [AnimatorResult](#animatorresult) | Animator结果接口。 |
109
110**错误码**:
111
112以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
113
114| 错误码ID | 错误信息 |
115| ------- | -------- |
116| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
117
118**示例:**
119
120> **说明:**
121>
122> 推荐通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[createAnimator](js-apis-arkui-UIContext.md#createanimator)接口明确UI上下文。
123
124<!--deprecated_code_no_check-->
125```ts
126import { Animator as animator, SimpleAnimatorOptions } from '@kit.ArkUI';
127let options: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200).duration(2000);
128animator.create(options);// 建议使用 UIContext.createAnimator()接口
129```
130
131### createAnimator<sup>(deprecated)</sup>
132
133createAnimator(options: AnimatorOptions): AnimatorResult
134
135创建动画
136
137从API version9开始不再维护,建议使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[createAnimator](js-apis-arkui-UIContext.md#createanimator)
138
139**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
140
141**参数:**
142
143| 参数名     | 类型                                  | 必填   | 说明      |
144| ------- | ----------------------------------- | ---- | ------- |
145| options | [AnimatorOptions](#animatoroptions) | 是    | 定义动画选项。 |
146
147**返回值:**
148
149| 类型                                | 说明            |
150| --------------------------------- | ------------- |
151| [AnimatorResult](#animatorresult) | Animator结果接口。 |
152
153**示例:**
154
155```ts
156import { Animator as animator } from '@kit.ArkUI';
157
158let options: AnimatorOptions = {
159  // xxx.js文件中不需要强调显式类型AnimatorOptions
160  duration: 1500,
161  easing: "friction",
162  delay: 0,
163  fill: "forwards",
164  direction: "normal",
165  iterations: 3,
166  begin: 200.0,
167  end: 400.0,
168};
169this.animator = animator.createAnimator(options);
170```
171
172## AnimatorResult
173
174定义Animator结果接口。
175
176### reset<sup>9+</sup>
177
178reset(options: AnimatorOptions): void
179
180更新当前animator动画。
181
182**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
183
184**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
185
186**参数:**
187
188| 参数名     | 类型                                  | 必填   | 说明      |
189| ------- | ----------------------------------- | ---- | ------- |
190| options | [AnimatorOptions](#animatoroptions) | 是    | 定义动画选项。 |
191
192**错误码:**
193
194以下错误码的详细介绍请参见[ohos.animator(动画)](errorcode-animator.md)错误码。
195
196| 错误码ID   | 错误信息 |
197| --------- | ------- |
198| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
199| 100001    | The specified page is not found or the object property list is not obtained.|
200
201
202**示例:**
203
204```ts
205import { Animator as animator, AnimatorOptions, AnimatorResult } from '@kit.ArkUI';
206import { BusinessError } from '@kit.BasicServicesKit';
207
208let options: AnimatorOptions = {
209  duration: 1500,
210  easing: "friction",
211  delay: 0,
212  fill: "forwards",
213  direction: "normal",
214  iterations: 3,
215  begin: 200.0,
216  end: 400.0
217};
218let optionsNew: AnimatorOptions = {
219  duration: 1500,
220  easing: "friction",
221  delay: 0,
222  fill: "forwards",
223  direction: "normal",
224  iterations: 5,
225  begin: 200.0,
226  end: 400.0
227};
228try {
229  let animatorResult: AnimatorResult | undefined = animator.create(options)
230  animatorResult.reset(optionsNew);
231} catch (error) {
232  let message = (error as BusinessError).message
233  let code = (error as BusinessError).code
234  console.error(`Animator reset failed, error code: ${code}, message: ${message}.`);
235}
236```
237
238### reset<sup>18+</sup>
239
240reset(options: AnimatorOptions \| [SimpleAnimatorOptions](#simpleanimatoroptions18)): void
241
242更新当前animator动画。与[reset](#reset9)相比,新增对[SimpleAnimatorOptions](#simpleanimatoroptions18)类型入参的支持。
243
244**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
245
246**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
247
248**参数:**
249
250| 参数名     | 类型                                  | 必填   | 说明      |
251| ------- | ----------------------------------- | ---- | ------- |
252| options | [AnimatorOptions](#animatoroptions) \| [SimpleAnimatorOptions](#simpleanimatoroptions18) | 是    | 定义动画选项。 |
253
254**错误码:**
255
256以下错误码的详细介绍请参考[通用错误码](../errorcode-universal.md)和[ohos.animator(动画)](errorcode-animator.md)错误码。
257
258| 错误码ID   | 错误信息 |
259| --------- | ------- |
260| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
261| 100001    | The specified page is not found or the object property list is not obtained.|
262
263**示例:**
264
265<!--deprecated_code_no_check-->
266```ts
267import { Animator as animator, AnimatorResult, AnimatorOptions, SimpleAnimatorOptions } from '@kit.ArkUI';
268let options: AnimatorOptions = {
269  duration: 1500,
270  easing: "ease",
271  delay: 0,
272  fill: "forwards",
273  direction: "normal",
274  iterations: 1,
275  begin: 100,
276  end: 200
277};
278let optionsNew: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200)
279  .duration(2000)
280  .iterations(3)
281  .delay(1000)
282let animatorResult:AnimatorResult = animator.create(options);
283animatorResult.reset(optionsNew);
284```
285
286### play
287
288play(): void
289
290启动动画。动画会保留上一次的播放状态,比如播放状态设置reverse后,再次播放会保留reverse的播放状态。
291
292**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
293
294**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
295
296**示例:**
297
298```ts
299animator.play();
300```
301
302### finish
303
304finish(): void
305
306结束动画。
307
308**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
309
310**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
311
312**示例:**
313
314```ts
315animator.finish();
316```
317
318### pause
319
320pause(): void
321
322暂停动画。
323
324**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
325
326**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
327
328**示例:**
329
330```ts
331animator.pause();
332```
333
334### cancel
335
336cancel(): void
337
338取消动画。
339
340**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
341
342**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
343
344**示例:**
345
346```ts
347animator.cancel();
348```
349
350### reverse
351
352reverse(): void
353
354以相反的顺序播放动画。使用interpolating-spring曲线时此接口无效。
355
356**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
357
358**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
359
360**示例:**
361
362```ts
363animator.reverse();
364```
365
366### onFrame<sup>12+</sup>
367
368onFrame: (progress: number) => void
369
370接收到帧时回调。
371
372**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
373
374**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
375
376**参数:**
377
378| 参数名      | 类型     | 必填   | 说明       |
379| -------- | ------ | ---- | -------- |
380| progress | number | 是    | 动画的当前值。<br/>取值范围为[AnimatorOptions](#animatoroptions)定义的[begin, end],默认取值范围为[0, 1]。 |
381
382**示例:**
383
384<!--deprecated_code_no_check-->
385```ts
386import { Animator as animator, AnimatorResult } from '@kit.ArkUI';
387
388let animatorResult: AnimatorResult | undefined = animator.create(options)
389animatorResult.onFrame = (value: number) => {
390  console.info("onFrame callback")
391}
392```
393
394### onFinish<sup>12+</sup>
395
396onFinish: () => void
397
398动画完成时回调。
399
400**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
401
402**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
403
404**示例:**
405
406<!--deprecated_code_no_check-->
407```ts
408import {Animator as animator, AnimatorResult } from '@kit.ArkUI';
409let animatorResult:AnimatorResult|undefined = animator.create(options)
410animatorResult.onFinish = ()=> {
411  console.info("onFinish callback")
412}
413```
414
415### onCancel<sup>12+</sup>
416
417onCancel: () => void
418
419动画被取消时回调。
420
421**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
422
423**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
424
425**示例:**
426
427<!--deprecated_code_no_check-->
428```ts
429import { Animator as animator, AnimatorResult } from '@kit.ArkUI';
430
431let animatorResult: AnimatorResult | undefined = animator.create(options)
432animatorResult.onCancel = () => {
433  console.info("onCancel callback")
434}
435```
436
437### onRepeat<sup>12+</sup>
438
439onRepeat: () => void
440
441动画重复时回调。
442
443**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
444
445**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
446
447**示例:**
448
449<!--deprecated_code_no_check-->
450```ts
451import { Animator as animator, AnimatorResult } from '@kit.ArkUI';
452
453let animatorResult: AnimatorResult | undefined = animator.create(options)
454animatorResult.onRepeat = () => {
455  console.info("onRepeat callback")
456}
457```
458
459### onframe<sup>(deprecated)</sup>
460
461> **说明:**
462>
463> 从API version 12开始废弃,推荐使用[onFrame](#onframe12)。
464
465onframe: (progress: number) => void
466
467接收到帧时回调。
468
469**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
470
471**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
472
473**参数:**
474
475| 参数名      | 类型     | 必填   | 说明       |
476| -------- | ------ | ---- | -------- |
477| progress | number | 是    | 动画的当前进度。 |
478
479**示例:**
480
481```ts
482import { Animator as animator, AnimatorResult } from '@kit.ArkUI';
483
484let animatorResult: AnimatorResult | undefined = animator.create(options)
485animatorResult.onframe = (value) => {
486  console.info("onframe callback")
487}
488```
489
490### onfinish<sup>(deprecated)</sup>
491
492> **说明:**
493>
494> 从API version 12开始废弃,推荐使用[onFinish](#onfinish12)。
495
496onfinish: () => void
497
498动画完成时回调。
499
500**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
501
502**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
503
504**示例:**
505
506```ts
507import { Animator as animator, AnimatorResult } from '@kit.ArkUI';
508
509let animatorResult: AnimatorResult | undefined = animator.create(options)
510animatorResult.onfinish = () => {
511  console.info("onfinish callback")
512}
513```
514
515### oncancel<sup>(deprecated)</sup>
516
517> **说明:**
518>
519> 从API version 12开始废弃,推荐使用[onCancel](#oncancel12)。
520
521
522oncancel: () => void
523
524动画被取消时回调。
525
526**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
527
528**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
529
530**示例:**
531
532<!--deprecated_code_no_check-->
533```ts
534import { Animator as animator, AnimatorResult } from '@kit.ArkUI';
535
536let animatorResult: AnimatorResult | undefined = animator.create(options)
537animatorResult.oncancel = () => {
538  console.info("oncancel callback")
539}
540```
541
542### onrepeat<sup>(deprecated)</sup>
543
544> **说明:**
545>
546> 从API version 12开始废弃,推荐使用[onRepeat](#onrepeat12)。
547
548onrepeat: () => void
549
550动画重复时回调。
551
552**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
553
554**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
555
556**示例:**
557
558```ts
559import { Animator as animator, AnimatorResult } from '@kit.ArkUI';
560
561let animatorResult: AnimatorResult | undefined = animator.create(options)
562animatorResult.onrepeat = () => {
563  console.info("onrepeat callback")
564}
565```
566
567### setExpectedFrameRateRange<sup>12+</sup>
568
569setExpectedFrameRateRange(rateRange: ExpectedFrameRateRange): void
570
571设置期望的帧率范围。
572
573**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
574
575**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
576
577**参数:**
578
579| 参数名           | 类型                                       | 必填 | 说明                          |
580| --------------- | ------------------------------------------ | ---- | -----------------------------|
581| rateRange       | [ExpectedFrameRateRange](../apis-arkui/arkui-ts/ts-explicit-animation.md#expectedframeraterange11)| 是   | 设置期望的帧率范围。|
582
583**示例:**
584
585<!--deprecated_code_no_check-->
586```ts
587import { Animator as animator, AnimatorResult } from '@kit.ArkUI';
588
589let animatorResult: AnimatorResult | undefined = animator.create({
590  duration: 2000,
591  easing: "ease",
592  delay: 0,
593  fill: "forwards",
594  direction: "normal",
595  iterations: 1,
596  begin: 100,
597  end: 200
598})
599let expectedFrameRate: ExpectedFrameRateRange = {
600  min: 0,
601  max: 120,
602  expected: 30
603}
604animatorResult.setExpectedFrameRateRange(expectedFrameRate);
605```
606
607### update<sup>(deprecated)</sup>
608
609update(options: AnimatorOptions): void
610
611更新当前动画器。
612
613从API version9开始不再维护,建议使用[reset<sup>9+</sup>](#reset9)。
614
615**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
616
617**参数:**
618
619| 参数名     | 类型                                  | 必填   | 说明      |
620| ------- | ----------------------------------- | ---- | ------- |
621| options | [AnimatorOptions](#animatoroptions) | 是    | 定义动画选项。 |
622
623**示例:**
624
625```ts
626animator.update(options);
627```
628
629## AnimatorOptions
630
631定义动画选项。
632
633**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
634
635**系统能力:** SystemCapability.ArkUI.ArkUI.Full
636
637| 名称       | 类型                                                        | 必填 | 说明                                                         |
638| ---------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
639| duration   | number                                                      | 是   | 动画播放的时长,单位毫秒。<br/> 取值范围:[0, +∞)                           |
640| easing     | string                                                      | 是   | 动画插值曲线,仅支持以下可选值:<br/>"linear":动画线性变化。<br/>"ease":动画开始和结束时的速度较慢,cubic-bezier(0.25、0.1、0.25、1.0)。<br/>"ease-in":动画播放速度先慢后快,cubic-bezier(0.42, 0.0, 1.0, 1.0)。<br/>"ease-out":动画播放速度先快后慢,cubic-bezier(0.0, 0.0, 0.58, 1.0)。<br/>"ease-in-out":动画播放速度先加速后减速,cubic-bezier(0.42, 0.0, 0.58, 1.0)。<br/>"fast-out-slow-in":标准曲线,cubic-bezier(0.4,0.0,0.2,1.0)。<br/>"linear-out-slow-in":减速曲线,cubic-bezier(0.0,0.0,0.2,1.0)。<br>"fast-out-linear-in":加速曲线,cubic-bezier(0.4, 0.0, 1.0, 1.0)。<br/>"friction":阻尼曲线,cubic-bezier(0.2, 0.0, 0.2, 1.0)。<br/>"extreme-deceleration":急缓曲线,cubic-bezier(0.0, 0.0, 0.0, 1.0)。<br/>"rhythm":节奏曲线,cubic-bezier(0.7, 0.0, 0.2, 1.0)。<br/>"sharp":锐利曲线,cubic-bezier(0.33, 0.0, 0.67, 1.0)。<br/>"smooth":平滑曲线,cubic-bezier(0.4, 0.0, 0.4, 1.0)。<br/>"cubic-bezier(x1,y1,x2,y2)":三次贝塞尔曲线,x1、x2的值必须处于0-1之间。例如"cubic-bezier(0.42,0.0,0.58,1.0)"。<br/>"steps(number,step-position)":阶梯曲线,number必须设置,为正整数,step-position参数可选,支持设置start或end,默认值为end。例如"steps(3,start)"。<br/>"interpolating-spring(velocity,mass,stiffness,damping)":插值弹簧曲线,从API version 11开始支持且仅在ArkTS中支持使用。velocity、mass、stiffness、damping都是数值类型,且mass、stiffness、damping参数均应该大于0,具体参数含义参考[插值弹簧曲线](./js-apis-curve.md#curvesinterpolatingspring10)。使用interpolating-spring时,duration不生效,由弹簧参数决定;fill、direction、iterations设置无效,fill固定设置为"forwards",direction固定设置为"normal",iterations固定设置为1,且对animator的[reverse](#reverse)函数调用无效。即animator使用interpolating-spring时只能正向播放1次。<br/>非法字符串时取:"ease"。 |
641| delay      | number                                                      | 是   | 动画延时播放时长,单位毫秒,设置为0时,表示不延时。设置为负数时动画提前播放,如果提前播放的时长大于动画总时长,动画直接过渡到终点。          |
642| fill       | 'none' \| 'forwards' \| 'backwards' \| 'both'               | 是   | 动画执行后是否恢复到初始状态,动画执行后,动画结束时的状态(在最后一个关键帧中定义)将保留。<br/>'none':在动画执行之前和之后都不会应用任何样式到目标上。<br/>'forwards':在动画结束后,目标将保留动画结束时的状态(在最后一个关键帧中定义)。<br/>'backwards':动画将在animation-delay期间应用第一个关键帧中定义的值。当animation-direction为'normal'或'alternate'时应用from关键帧中的值,当animation-direction为'reverse'或'alternate-reverse'时应用to关键帧中的值。<br/>'both':动画将遵循forwards和backwards的规则,从而在两个方向上扩展动画属性。 |
643| direction  | 'normal' \| 'reverse' \| 'alternate' \| 'alternate-reverse' | 是   | 动画播放模式。<br/>'normal': 动画正向循环播放。<br/>'reverse': 动画反向循环播放。<br/>'alternate':动画交替循环播放,奇数次正向播放,偶数次反向播放。<br/>'alternate-reverse':动画反向交替循环播放,奇数次反向播放,偶数次正向播放。 |
644| iterations | number                                                      | 是   | 动画播放次数。设置为0时不播放,设置为-1时无限次播放,设置大于0时为播放次数。<br/>**说明:** 设置为除-1外其他负数视为无效取值,无效取值动画默认播放1次。 |
645| begin      | number                                                      | 是   | 动画插值起点。                                               |
646| end        | number                                                      | 是   | 动画插值终点。                                               |
647
648## SimpleAnimatorOptions<sup>18+</sup>
649
650animator简易动画参数对象。与AnimatorOptions相比,部分动画参数有默认值,可不设置。
651
652### constructor<sup>18+</sup>
653
654constructor(begin: number, end: number)
655
656SimpleAnimatorOptions的构造函数。
657
658**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
659
660**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
661
662**参数:**
663
664| 参数名       | 类型                                                        | 必填 | 说明                                                         |
665| ---------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
666|  begin      | number                                                      | 是   | 动画插值起点。                                               |
667|  end        | number                                                      | 是   | 动画插值终点。
668
669**示例:**
670
671```ts
672import { Animator as animator, AnimatorResult, SimpleAnimatorOptions } from '@kit.ArkUI';
673
674let options: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200); // 动画插值过程从100到200,其余动画参数使用默认值。
675let animatorResult:AnimatorResult = animator.create(options);
676```
677
678### duration<sup>18+</sup>
679
680duration(duration: number): SimpleAnimatorOptions
681
682设置animator动画时长。
683
684**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
685
686**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
687
688**参数:**
689
690| 参数名     | 类型                                  | 必填   | 说明      |
691| ------- | ----------------------------------- | ---- | ------- |
692| duration | number | 是    | 设置动画时长,单位毫秒。<br/>默认值:1000 |
693
694**返回值:**
695
696| 类型                                | 说明            |
697| --------------------------------- | ------------- |
698| [SimpleAnimatorOptions](#simpleanimatoroptions18) | Animator简易动画参数对象。 |
699
700**示例:**
701
702```ts
703import { Animator as animator, AnimatorResult, SimpleAnimatorOptions } from '@kit.ArkUI';
704
705let options: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200).duration(500);
706let animatorResult:AnimatorResult = animator.create(options);
707```
708
709### easing<sup>18+</sup>
710
711easing(curve: string): SimpleAnimatorOptions
712
713设置animator动画插值曲线。
714
715**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
716
717**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
718
719**参数:**
720
721| 参数名     | 类型                                  | 必填   | 说明      |
722| ------- | ----------------------------------- | ---- | ------- |
723| curve | string | 是    | 设置animator动画插值曲线,具体说明参考[AnimatorOptions]。<br/>默认值:“ease” |
724
725**返回值:**
726
727| 类型                                | 说明            |
728| --------------------------------- | ------------- |
729| [SimpleAnimatorOptions](#simpleanimatoroptions18) | Animator简易动画参数对象。 |
730
731**示例:**
732
733```ts
734import { Animator as animator, AnimatorResult, SimpleAnimatorOptions } from '@kit.ArkUI';
735
736let options: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200).easing("ease-in");
737let animatorResult:AnimatorResult = animator.create(options);
738```
739
740### delay<sup>18+</sup>
741
742delay(delay: number): SimpleAnimatorOptions
743
744设置animator动画播放时延。
745
746**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
747
748**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
749
750**参数:**
751
752| 参数名     | 类型                                  | 必填   | 说明      |
753| ------- | ----------------------------------- | ---- | ------- |
754| delay | number | 是    | 设置animator动画播放时延,单位毫秒,设置为0时,表示不延时。设置为负数时动画提前播放,如果提前播放的时长大于动画总时长,动画直接过渡到终点。<br/>默认值:0 |
755
756**返回值:**
757
758| 类型                                | 说明            |
759| --------------------------------- | ------------- |
760| [SimpleAnimatorOptions](#simpleanimatoroptions18) | Animator简易动画参数对象。 |
761
762**示例:**
763
764```ts
765import { Animator as animator, AnimatorResult, SimpleAnimatorOptions } from '@kit.ArkUI';
766
767let options: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200).delay(500);
768let animatorResult:AnimatorResult = animator.create(options);
769```
770
771### fill<sup>18+</sup>
772
773fill(fillMode: [FillMode](./arkui-ts/ts-appendix-enums.md#fillmode)): SimpleAnimatorOptions
774
775设置animator动画填充方式。
776
777**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
778
779**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
780
781**参数:**
782
783| 参数名     | 类型                                  | 必填   | 说明      |
784| ------- | ----------------------------------- | ---- | ------- |
785| fillMode | [FillMode](./arkui-ts/ts-appendix-enums.md#fillmode) | 是    | 设置animator动画填充方式,影响动画delay期间和结束时的表现。<br/>默认值:FillMode.Forwards |
786
787**返回值:**
788
789| 类型                                | 说明            |
790| --------------------------------- | ------------- |
791| [SimpleAnimatorOptions](#simpleanimatoroptions18) | Animator简易动画参数对象。 |
792
793**示例:**
794
795```ts
796import { Animator as animator, AnimatorResult, SimpleAnimatorOptions } from '@kit.ArkUI';
797
798let options: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200).fill(FillMode.Forwards);
799let animatorResult:AnimatorResult = animator.create(options);
800```
801
802### direction<sup>18+</sup>
803
804direction(direction: [PlayMode](./arkui-ts/ts-appendix-enums.md#playmode)): SimpleAnimatorOptions
805
806设置animator动画播放方向。
807
808**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
809
810**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
811
812**参数:**
813
814| 参数名     | 类型                                  | 必填   | 说明      |
815| ------- | ----------------------------------- | ---- | ------- |
816| direction | [PlayMode](./arkui-ts/ts-appendix-enums.md#playmode) | 是    | 设置animator动画播放方向。<br/>默认值:PlayMode.Normal |
817
818**返回值:**
819
820| 类型                                | 说明            |
821| --------------------------------- | ------------- |
822| [SimpleAnimatorOptions](#simpleanimatoroptions18) | Animator简易动画参数对象。 |
823
824**示例:**
825
826```ts
827import { Animator as animator, AnimatorResult, SimpleAnimatorOptions } from '@kit.ArkUI';
828
829let options: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200).direction(PlayMode.Alternate);
830let animatorResult:AnimatorResult = animator.create(options);
831```
832
833### iterations<sup>18+</sup>
834
835iterations(iterations: number): SimpleAnimatorOptions
836
837设置animator动画播放次数。
838
839**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
840
841**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
842
843**参数:**
844
845| 参数名     | 类型                                  | 必填   | 说明      |
846| ------- | ----------------------------------- | ---- | ------- |
847| iterations | number | 是    | 设置animator动画播放次数,设置为0时不播放,设置为-1时无限次播放。<br/>默认值:1 |
848
849**返回值:**
850
851| 类型                                | 说明            |
852| --------------------------------- | ------------- |
853| [SimpleAnimatorOptions](#simpleanimatoroptions18) | Animator简易动画参数对象。 |
854
855**示例:**
856
857```ts
858import { Animator as animator, AnimatorResult, SimpleAnimatorOptions } from '@kit.ArkUI';
859
860let options: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200).iterations(3);
861let animatorResult:AnimatorResult = animator.create(options);
862```
863
864## 完整示例
865### 基于JS扩展的类Web开发范式
866
867```html
868<!-- hml -->
869<div class="container">
870  <div class="Animation" style="height: {{divHeight}}px; width: {{divWidth}}px; background-color: red;" onclick="Show">
871  </div>
872</div>
873```
874
875<!--deprecated_code_no_check-->
876```ts
877import { Animator as animator, AnimatorResult } from '@kit.ArkUI';
878import { BusinessError } from '@kit.BasicServicesKit';
879
880let DataTmp: Record<string, Animator> = {
881  'divWidth': 200,
882  'divHeight': 200,
883  'animator': animator
884}
885
886class Tmp {
887  data: animator = DataTmp
888  onInit: Function = () => {
889  }
890  Show: Function = () => {
891  }
892}
893
894class DateT {
895  divWidth: number = 0
896  divHeight: number = 0
897  animator: AnimatorResult | null = null
898}
899
900(Fn: (v: Tmp) => void) => {
901  Fn({
902    data: DataTmp,
903    onInit() {
904      let options: AnimatorOptions = {
905        duration: 1500,
906        easing: "friction",
907        delay: 0,
908        fill: "forwards",
909        direction: "normal",
910        iterations: 2,
911        begin: 200.0,
912        end: 400.0
913      };
914      let DataTmp: DateT = {
915        divWidth: 200,
916        divHeight: 200,
917        animator: null
918      }
919      DataTmp.animator = animator.create(options);
920    },
921    Show() {
922      let options1: AnimatorOptions = {
923        duration: 1500,
924        easing: "friction",
925        delay: 0,
926        fill: "forwards",
927        direction: "normal",
928        iterations: 2,
929        begin: 0,
930        end: 400.0,
931      };
932      let DataTmp: DateT = {
933        divWidth: 200,
934        divHeight: 200,
935        animator: null
936      }
937      try {
938        DataTmp.animator = animator.create(options1);
939        DataTmp.animator.reset(options1);
940      } catch (error) {
941        let message = (error as BusinessError).message
942        let code = (error as BusinessError).code
943        console.error(`Animator reset failed, error code: ${code}, message: ${message}.`);
944      }
945      let _this = DataTmp;
946      if (DataTmp.animator) {
947        DataTmp.animator.onFrame = (value: number) => {
948          _this.divWidth = value;
949          _this.divHeight = value;
950        };
951        DataTmp.animator.play();
952      }
953    }
954  })
955}
956```
957
958  ![zh-cn_image_00007](figures/zh-cn_image_00007.gif)
959
960### 基于ArkTS扩展的声明式开发范式
961
962> **说明:**
963>
964> 推荐通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[createAnimator](js-apis-arkui-UIContext.md#createanimator)接口明确UI上下文。
965
966<!--deprecated_code_no_check-->
967```ts
968import { Animator as animator, AnimatorResult } from '@kit.ArkUI';
969
970@Entry
971@Component
972struct AnimatorTest {
973  private TAG: string = '[AnimatorTest]'
974  private backAnimator: AnimatorResult | undefined = undefined
975  private flag: boolean = false
976  @State wid: number = 100
977  @State hei: number = 100
978
979  create() {
980    this.backAnimator = animator.create({
981      // 建议使用 this.getUIContext.createAnimator()接口
982      duration: 2000,
983      easing: "ease",
984      delay: 0,
985      fill: "forwards",
986      direction: "normal",
987      iterations: 1,
988      begin: 100,
989      end: 200
990    })
991    this.backAnimator.onFinish = () => {
992      this.flag = true
993      console.info(this.TAG, 'backAnimator onfinish')
994    }
995    this.backAnimator.onRepeat = () => {
996      console.info(this.TAG, 'backAnimator repeat')
997    }
998    this.backAnimator.onCancel = () => {
999      console.info(this.TAG, 'backAnimator cancel')
1000    }
1001    this.backAnimator.onFrame = (value: number) => {
1002      this.wid = value
1003      this.hei = value
1004    }
1005  }
1006
1007  aboutToDisappear() {
1008    // 由于backAnimator在onframe中引用了this, this中保存了backAnimator,
1009    // 在自定义组件消失时应该将保存在组件中的backAnimator置空,避免内存泄漏
1010    this.backAnimator = undefined;
1011  }
1012
1013  build() {
1014    Column() {
1015      Column() {
1016        Column()
1017          .width(this.wid)
1018          .height(this.hei)
1019          .backgroundColor(Color.Red)
1020      }
1021      .width('100%')
1022      .height(300)
1023
1024      Column() {
1025        Row() {
1026          Button('create')
1027            .fontSize(30)
1028            .fontColor(Color.Black)
1029            .onClick(() => {
1030              this.create()
1031            })
1032        }
1033        .padding(10)
1034
1035        Row() {
1036          Button('play')
1037            .fontSize(30)
1038            .fontColor(Color.Black)
1039            .onClick(() => {
1040              this.flag = false
1041              if (this.backAnimator) {
1042                this.backAnimator.play()
1043              }
1044            })
1045        }
1046        .padding(10)
1047
1048        Row() {
1049          Button('pause')
1050            .fontSize(30)
1051            .fontColor(Color.Black)
1052            .onClick(() => {
1053              if (this.backAnimator) {
1054                this.backAnimator.pause()
1055              }
1056            })
1057        }
1058        .padding(10)
1059
1060        Row() {
1061          Button('finish')
1062            .fontSize(30)
1063            .fontColor(Color.Black)
1064            .onClick(() => {
1065              this.flag = true
1066              if (this.backAnimator) {
1067                this.backAnimator.finish()
1068              }
1069            })
1070        }
1071        .padding(10)
1072
1073        Row() {
1074          Button('reverse')
1075            .fontSize(30)
1076            .fontColor(Color.Black)
1077            .onClick(() => {
1078              this.flag = false
1079              if (this.backAnimator) {
1080                this.backAnimator.reverse()
1081              }
1082            })
1083        }
1084        .padding(10)
1085
1086        Row() {
1087          Button('cancel')
1088            .fontSize(30)
1089            .fontColor(Color.Black)
1090            .onClick(() => {
1091              if (this.backAnimator) {
1092                this.backAnimator.cancel()
1093              }
1094            })
1095        }
1096        .padding(10)
1097
1098        Row() {
1099          Button('reset')
1100            .fontSize(30)
1101            .fontColor(Color.Black)
1102            .onClick(() => {
1103              if (this.flag) {
1104                this.flag = false
1105                if (this.backAnimator) {
1106                  this.backAnimator.reset({
1107                    duration: 3000,
1108                    easing: "ease-in",
1109                    delay: 0,
1110                    fill: "forwards",
1111                    direction: "alternate",
1112                    iterations: 3,
1113                    begin: 100,
1114                    end: 300
1115                  })
1116                }
1117              } else {
1118                console.info(this.TAG, 'Animation not ended')
1119              }
1120            })
1121        }
1122        .padding(10)
1123      }
1124    }
1125  }
1126}
1127```
1128
1129### 位移动画示例(简易入参)
1130
1131```ts
1132import { AnimatorResult, SimpleAnimatorOptions } from '@kit.ArkUI';
1133
1134@Entry
1135@Component
1136struct AnimatorTest {
1137  private TAG: string = '[AnimatorTest]'
1138  private backAnimator: AnimatorResult | undefined = undefined
1139  private flag: boolean = false
1140  @State translate_: number = 0
1141
1142  create() {
1143    this.backAnimator = this.getUIContext()?.createAnimator(
1144      new SimpleAnimatorOptions(0, 100)
1145    )
1146    this.backAnimator.onFinish = ()=> {
1147      this.flag = true
1148      console.info(this.TAG, 'backAnimator onfinish')
1149    }
1150    this.backAnimator.onFrame = (value:number)=> {
1151      this.translate_ = value
1152    }
1153  }
1154
1155  aboutToDisappear() {
1156    // 由于backAnimator在onFrame中引用了this, this中保存了backAnimator,
1157    // 在自定义组件消失时应该将保存在组件中的backAnimator置空,避免内存泄漏
1158    this.backAnimator = undefined;
1159  }
1160
1161  build() {
1162    Column() {
1163      Column() {
1164        Column()
1165          .width(100)
1166          .height(100)
1167          .translate({x: this.translate_})
1168          .backgroundColor(Color.Green)
1169      }
1170      .width('100%')
1171      .height(300)
1172
1173      Column() {
1174        Column() {
1175          Button('create')
1176            .fontSize(30)
1177            .fontColor(Color.Black)
1178            .onClick(() => {
1179              this.create()
1180            })
1181        }
1182        .padding(10)
1183
1184        Column() {
1185          Button('play')
1186            .fontSize(30)
1187            .fontColor(Color.Black)
1188            .onClick(() => {
1189              this.flag = false
1190              if(this.backAnimator){
1191                this.backAnimator.play()
1192              }
1193            })
1194        }
1195        .padding(10)
1196
1197        Column() {
1198          Button('reset')
1199            .fontSize(30)
1200            .fontColor(Color.Black)
1201            .onClick(() => {
1202              if (this.flag) {
1203                this.flag = false
1204                if(this.backAnimator){
1205                  this.backAnimator.reset(
1206                    new SimpleAnimatorOptions(0, -100)
1207                      .duration(2000)
1208                      .easing("ease-in")
1209                      .fill(FillMode.Forwards)
1210                      .direction(PlayMode.Alternate)
1211                      .iterations(2)
1212                  )
1213                }
1214              } else {
1215                console.info(this.TAG, 'Animation not ended')
1216              }
1217            })
1218        }
1219        .padding(10)
1220      }
1221    }
1222  }
1223}
1224```
1225
1226![animator](figures/animator.gif)
1227