目录

如何实现图片透明度渐变动画

问题现象

如何在Image组件切换时,形成透明度由高到低的动画效果?

背景知识

解决方案

可以利用if条件语句来控制Image的展示,配合关键帧动画修改图片的透明度,从而达成透明度渐变动画,示例代码参考如下:

@Entry
@Component
struct ImageOpacityAnimate {
  @State showOpacity: number = 1;
  @State showIndex: number = 0;
  data: ResourceStr[] = [];

  aboutToAppear() {
    // 图片资源需自行替换
    this.data.push($r('app.media.img1'));
    this.data.push($r('app.media.img2'));
    this.data.push($r('app.media.startIcon'));
  }

  build() {
    Column({ space: 5 }) {
      Column() {
        ForEach(this.data, (item: ResourceStr, index: number) => {
          if (this.showIndex === index) {
            Image(item)
              .width(200)
              .height(200)
              .opacity(this.showOpacity);
          }
        });
      };

      Button('click').onClick(() => {
        this.show();
      });
    }
    .width('100%');
  }

  show() {
    this.getUIContext().keyframeAnimateTo({
      iterations: 1,
      onFinish: () => {
        // 递归调用
        this.show();
      }
    },
      [
        {
          duration: 1000,
          event: () => {
            // 第一段动画把图片透明度从1变成0
            this.showOpacity = 0;
          }
        },
        {
          duration: 500,
          event: () => {
            // 第二段动画完成图片切换
            this.showIndex = (this.showIndex + 1) % this.data.length;
          }
        },
        {
          duration: 1000,
          event: () => {
            // 第三段动画把图片透明度从0变成1
            this.showOpacity = 1;
          }
        }
      ]);
  }
}