除了使用属性动画实现动画效果外,ArkTS 中还有以下多种方式可以实现动画效果:
使用 Animation 组件
基本原理:通过在组件树中直接使用Animation组件,并配置其属性来实现动画效果。
示例代码:
import { Animation, Component } from '@ohos/animate';
@Component
struct MyComponent {
private anim: Animation = new Animation();
build() {
this.anim.duration = 2000;
this.anim.easing = 'ease-in-out';
this.anim.iterations = 1;
this.anim.keyframes = [
{ percent: 0, translateX: 0, translateY: 0 },
{ percent: 0.5, translateX: 100, translateY: 50 },
{ percent: 1, translateX: 200, translateY: 100 }
];
const rect = ;
rect.animation = this.anim;
return {rect} ;
}
}
使用 @keyframes 规则
- 基本原理:类似于 CSS 中的@keyframes规则,在 ArkTS 中可以使用@keyframes定义关键帧动画,然后将其应用到组件的style属性中。
- 示例代码:
@Component
struct MyComponent {
build() {
const keyframes = `
@keyframes myAnimation {
0% {
transform: translateX(0px) translateY(0px);
}
50% {
transform: translateX(100px) translateY(50px);
}
100% {
transform: translateX(200px) translateY(100px);
}
}
`;
const rect = ;
return {rect} ;
}
}
使用 Transition 组件
- 基本原理:Transition组件用于在组件的显示和隐藏状态之间添加过渡动画效果。
- 示例代码:
import { Transition, Component } from '@ohos/animate';
@Component
struct MyComponent {
private show: boolean = false;
build() {
const rect = ;
const transition =
{this.show? rect : null}
;
return
{transition}
;
}
}
使用 AnimateTo 和 AnimateBy 函数
- 基本原理:AnimateTo函数用于将组件的属性从当前值动画到指定的值,AnimateBy函数则是在组件当前属性值的基础上进行相对的动画变化。
- 示例代码:
import { AnimateTo, AnimateBy, Component } from '@ohos/animate';
@Component
struct MyComponent {
private myComponent: Component | null = null;
build() {
const rect = this.myComponent = el as Component} width="100" height="100" backgroundColor="#FF0000"> ;
const button1 = ;
const button2 = ;
return {rect}{button1}{button2} ;
}
}