目录

实现相机录像按钮动效

问题现象

如何实现HarmonyOS系统相机录像开始和结束时的按钮动画?

背景知识

解决方案

  1. 创建boolean类型的show变量,用于实现动画的转换,Row组件的属性如宽、高、背景颜色、边框颜色等依据show变量值的真假而改变。
  2. 为Row组件添加onClick事件,通过getUIContext方法获取UIContext实例,调用animateTo函数,将动画的持续时间设置为300ms,并对show变量的值取反,即可实现动态切换的效果。
完整参考示例如下:
@Entry
@Component
struct CameraAnimationEffect {
  @State show: boolean = false;

  build() {
    Column() {
      Row() {
        Row()
          .width(this.show ? 40 : 80)
          .height(this.show ? 40 : 80)
          .backgroundColor(Color.Red)
          .borderRadius(this.show ? 10 : 80)
          .borderColor(this.show ? Color.Red : Color.White)
          .borderWidth(20);
      }
      .width(100)
      .height(100)
      .justifyContent(FlexAlign.Center)
      .backgroundColor(Color.Transparent)
      .borderRadius(100)
      .borderColor(Color.White)
      .borderWidth(2)
      // 添加点击事件
      .onClick(() => {
        this.getUIContext().animateTo({
          duration: 300
        }, () => {
          this.show = !this.show;
        });
      });
    }
    .width('100%')
    .height('100%')
    .alignItems(HorizontalAlign.Center)
    .justifyContent(FlexAlign.Center)
    .backgroundColor(Color.Black);
  }
}

总结

通过boolean类型的变量,实现组件属性的动态切换,可实现相机录像按钮的动态切换效果。