鸿蒙Next开发中如何实现扫光效果

在鸿蒙Next应用开发中,如何实现类似扫光的高亮动画效果?我想在按钮或文字上添加一道横向或纵向滑过的光效,类似金属反光的效果,但不太清楚具体该用哪些组件或动画API来实现。是否需要自定义绘制?还是可以利用现有的属性动画或渐变效果组合实现?希望能提供具体的代码示例或实现思路。

2 回复

鸿蒙Next里实现扫光效果?简单!用Canvas画个矩形,加个渐变LinearGradient,再让rotate属性动起来,扫光就来了!记得控制动画频率,别闪瞎用户的眼睛~(代码?自己查文档去,我不能抢IDE的饭碗!)

更多关于鸿蒙Next开发中如何实现扫光效果的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在鸿蒙Next开发中,可以通过自定义绘制实现扫光效果,通常结合Canvas和动画组件完成。以下是核心实现步骤和示例代码:

实现思路

  1. 绘制渐变矩形:使用Canvas绘制一个线性渐变矩形作为扫光层。
  2. 添加动画:通过属性动画(如AnimatorPath)控制渐变的位置变化,形成扫动效果。
  3. 叠加到目标组件:将扫光层覆盖到需要特效的视图上(如文本、图片)。

示例代码

import { Curves } from '@ohos.curves';
import { Animator, AnimatorPath } from '@ohos.animator';

// 1. 自定义扫光组件
@Component
struct ShineEffect {
  private controller: CanvasRenderingContext2D = new CanvasRenderingContext2D();
  private animator: AnimatorPath = new AnimatorPath();
  private offsetX: number = -1; // 渐变起始位置

  build() {
    Column() {
      // 目标视图(示例为文本)
      Text('鸿蒙Next')
        .fontSize(30)
        .textAlign(TextAlign.Center)
        .width('100%')
        .height(50)

      // 扫光层(覆盖在目标上方)
      Canvas(this.controller)
        .width('100%')
        .height(50)
        .onReady(() => {
          this.startAnimation();
        })
    }
  }

  // 2. 绘制渐变图形
  private drawShine() {
    const gradient = this.controller.createLinearGradient(0, 0, 200, 0);
    gradient.addColorStop(0.0, '#00000000');     // 透明
    gradient.addColorStop(0.4, '#FFFFFF99');     // 高亮
    gradient.addColorStop(0.6, '#FFFFFF99');     // 高亮
    gradient.addColorStop(1.0, '#00000000');     // 透明

    this.controller.clearRect(0, 0, 300, 50);
    this.controller.fillStyle = gradient;
    this.controller.fillRect(this.offsetX, 0, 200, 50); // 动态位置矩形
  }

  // 3. 创建动画
  private startAnimation() {
    this.animator = new AnimatorPath({
      duration: 1500,
      curve: Curves.EASE_IN_OUT
    });

    this.animator.onFrame((value: number) => {
      this.offsetX = 300 * value - 100; // 从左侧扫到右侧
      this.drawShine();
    });

    this.animator.setIteration(Number.POSITIVE_INFINITY); // 无限循环
    this.animator.play();
  }
}

关键说明

  • 渐变参数:通过调整addColorStop的值和颜色可改变扫光宽度和透明度。
  • 动画轨迹:修改offsetX计算公式可调整扫光方向和速度。
  • 性能优化:对静态内容建议使用Canvas,动态复杂效果可考虑Lottie动画。

使用方式

在页面中直接引用组件:

@Entry
@Component
struct Index {
  build() {
    Column() {
      ShineEffect()
    }
  }
}

通过调整渐变尺寸、动画时长和曲线,可适配不同场景的扫光需求。

回到顶部