文档开发者中心
我的
|

HarmonyOS 5

如何实现图片走马灯的效果

如何实现图片走马灯的效果?
点赞
收藏
回复
4
分享
举报
浏览199 发布于2025-11-14 08:11广东
全部评论
最多点赞
最新发布
最早发布

使用Row或Flex容器横向排列多张图片

收起
自动换行
深色代码主题
复制
Row() {
  ForEach(this.imageList, (item: Resource) => {
    Image(item).width(200).height(200).margin(10)
  })
}
.width('100%')

通过属性动画实现连续滚动

收起
自动换行
深色代码主题
复制
@State offsetX: number = 0

// 启动动画
animateScroll() {
  animateTo({
    duration: 5000,    // 动画时长
    curve: Curve.Linear,
    iterations: -1     // 无限循环
  }, () => {
    this.offsetX = -this.contentWidth // 位移至图片总宽度
  })
}

官方也有参考demo

收起
自动换行
深色代码主题
复制
// 将图片沿着水平方向平移offsetX的距离,设置超时时间duration,平移距离offsetX>=0或者小于等于2倍的contentWidth宽度时,则将平移距离offsetX进行重置可实现图片循环滚动,
@Entry
@Component
struct MarqueeExample4 {
  @State isAnimating: boolean = false;
  duration: number = 20;
  @State offsetX: number = 100; // 设置偏移,可使界面左右都能滑动
  contentWidth: number = 100; // 数据内容宽度初始值
  autoOffset: number = 1; // 偏移值

  build() {
    Row({ space: 2 }) {
      ForEach(['', '', ''], () => {
        Row() {
          this.currentItem();
        }
        .translate({ x: this.offsetX })
      }, () => {
        return `xxxx`;
      })
    }
    .onAppear(() => {
      // 在组件出现时获取高度
      this.startScrolling();
    })
    .width('100%').backgroundColor(Color.Transparent).height('100%')
  }

  @Builder
  currentItem() {
    Image($r('app.media.startIcon')).width(100).height(100); // 此处'app.media.startIcon'仅作示例,请开发者自行更换
    Image($r('app.media.startIcon')).width(100).height(100);
    Image($r('app.media.startIcon')).width(100).height(100);
    Image($r('app.media.startIcon')).width(100).height(100);
    Image($r('app.media.startIcon')).width(100).height(100);
    Image($r('app.media.startIcon')).width(100).height(100);
    Image($r('app.media.startIcon')).width(100).height(100);
    Image($r('app.media.startIcon')).width(100).height(100);
  }

  private startScrolling() {
    this.isAnimating = true;
    this.animate();
  }

  private animate() {
    if (!this.isAnimating) {
      return;
    }
    setTimeout(() => {
      // 继续当前方向的滚动
      this.offsetX = this.offsetX - this.autoOffset;
      // 检查是否需要重置位置
      if (this.offsetX >= 0 || this.offsetX <= -this.contentWidth * 2) {
        this.offsetX = -this.contentWidth;
      }
      if (this.isAnimating) {
        this.animate();
      }
    }, this.duration);
  }
}

参考地址

https://developer.huawei.com/consumer/cn/doc/architecture-guides/shaking_to_dialog_1-ts_59-0000002393023572

展开全部
4楼回复于2025-11-18 01:49 来自安徽

代码 实现

收起
自动换行
深色代码主题
复制
@Entry
@Component
struct ImageMarquee {
  // 配置图片资源(替换为自己的应用内图片)
  private imageSources = [
    $r('app.media.img1'),
    $r('app.media.img2'),
    $r('app.media.img3')
  ];
  // 控制当前显示索引(支持手动切换)
  @State currentIndex: number = 0;

  build() {
    Column() {
      // 1. 图片走马灯核心容器
      Swiper({
        index: this.currentIndex, // 绑定当前索引
        onChange: (index) => this.currentIndex = index // 滑动后更新索引
      }) {
        // 循环渲染图片
        ForEach(this.imageSources, (imgRes, idx) => {
          Image(imgRes)
            .width('100%') // 适配容器宽度
            .height(200) // 固定走马灯高度(可自定义)
            .objectFit(ImageFit.Cover) // 保持比例填充容器,避免变形
            .radius(8) // 圆角优化(可选)
        }, (imgRes) => imgRes.id) // 唯一标识(基于图片资源ID)
      }
      .displayMode(SwiperDisplayMode.STRETCH) // 自适应容器
      .loop(true) // 无限循环
      .autoPlay(true) // 自动轮播
      .interval(3000) // 切换间隔(3秒,可调整)
      .indicator(true) // 显示底部指示器
      .indicatorStyle({ // 自定义指示器样式
        color: Color.Gray, // 未选中颜色
        selectedColor: Color.Blue, // 选中颜色
        size: 8 // 指示器大小(vp)
      })
      .vertical(false) // 水平方向轮播(true为垂直)
      .margin(16)

      // 2. 手动切换按钮(可选,增强交互)
      Row() {
        Button('上一张')
          .onClick(() => {
            // 取模运算实现循环
            this.currentIndex = (this.currentIndex - 1 + this.imageSources.length) % this.imageSources.length;
          })
        Button('下一张')
          .onClick(() => {
            this.currentIndex = (this.currentIndex + 1) % this.imageSources.length;
          })
      }
      .spacing(20)
    }
    .width('100%')
    .padding(16)
  }
}

关键配置说明(按需调整)

参数 作用 推荐值
loop(true) 是否无限循环 true(走马灯核心需求)
autoPlay(true) 是否自动轮播 true(默认开启)
interval(3000) 自动切换间隔(毫秒) 2000-5000(避免过快)
objectFit(ImageFit.Cover) 图片适配方式 Cover(保持比例不拉伸)
indicatorStyle 指示器样式(颜色 / 大小) 按 UI 风格自定义
vertical(false) 轮播方向 false(水平)/true(垂直)

优化点 & 注意事项

  1. 图片适配:添加objectFit和radius,解决图片变形、样式粗糙问题;
  2. 交互增强:绑定currentIndex+ 手动按钮,支持 “自动轮播 + 手动切换” 双模式;
  3. 资源复用:图片数组抽离为变量,替换资源更便捷;
  4. 性能优化:
    • 图片数量 > 5 张时,建议开启懒加载:Swiper({ lazyLoad: true });
    • 页面销毁时无需额外清理(Swiper 内部已处理),复杂场景可在aboutToDisappear中设置autoPlay(false);
  5. 样式兼容:容器宽高用%+ 固定值组合,适配不同屏幕尺寸;
  6. 资源引用:图片需放在main_pages同级的media目录,用$r('app.media.xxx')格式引用。

扩展场景

 
展开全部
3楼编辑于2025-11-17 15:40 来自广东

使用Row组件的.translate({x})属性平移方式实现图片的跑马灯效果。

收起
自动换行
深色代码主题
复制
// 将图片沿着水平方向平移offsetX的距离,设置超时时间duration,平移距离offsetX>=0或者小于等于2倍的contentWidth宽度时,则将平移距离offsetX进行重置可实现图片循环滚动,
@Entry
@Component
struct MarqueeExample4 {
  @State isAnimating: boolean = false;
  duration: number = 20;
  @State offsetX: number = 100; // 设置偏移,可使界面左右都能滑动
  contentWidth: number = 100; // 数据内容宽度初始值
  autoOffset: number = 1; // 偏移值

  build() {
    Row({ space: 2 }) {
      ForEach(['', '', ''], () => {
        Row() {
          this.currentItem();
        }
        .translate({ x: this.offsetX })
      }, () => {
        return `xxxx`;
      })
    }
    .onAppear(() => {
      // 在组件出现时获取高度
      this.startScrolling();
    })
    .width('100%').backgroundColor(Color.Transparent).height('100%')
  }

  @Builder
  currentItem() {
    Image($r('app.media.startIcon')).width(100).height(100); // 此处'app.media.startIcon'仅作示例,请开发者自行更换
    Image($r('app.media.startIcon')).width(100).height(100);
    Image($r('app.media.startIcon')).width(100).height(100);
    Image($r('app.media.startIcon')).width(100).height(100);
    Image($r('app.media.startIcon')).width(100).height(100);
    Image($r('app.media.startIcon')).width(100).height(100);
    Image($r('app.media.startIcon')).width(100).height(100);
    Image($r('app.media.startIcon')).width(100).height(100);
  }

  private startScrolling() {
    this.isAnimating = true;
    this.animate();
  }

  private animate() {
    if (!this.isAnimating) {
      return;
    }
    setTimeout(() => {
      // 继续当前方向的滚动
      this.offsetX = this.offsetX - this.autoOffset;
      // 检查是否需要重置位置
      if (this.offsetX >= 0 || this.offsetX <= -this.contentWidth * 2) {
        this.offsetX = -this.contentWidth;
      }
      if (this.isAnimating) {
        this.animate();
      }
    }, this.duration);
  }
}

效果预览:

更多跑马灯效果可参考:跑马灯效果实现

展开全部
2楼回复于2025-11-17 08:08 来自广东

使用Swiper组件,循环渲染要播放的图片,然后设置swiper组件的.autoplay属性

滑块视图容器

1楼回复于2025-11-14 08:16 来自广东
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要提问题

了解社区公约,与您携手共创和谐专业的开发者社区。