实现图片视频预览功能鸿蒙示例代码

鸿蒙场景化示例代码技术工程师
发布于 2025-3-4 17:28
1.8w浏览
0收藏

本文原创发布在华为开发者社区

介绍

本示例基于组合手势实现图片视频的预览功能,支持双击缩放图片,双指缩放图片,拖动图片以及点击视频进行预览。

实现图片视频预览功能源码链接

效果预览

实现图片视频预览功能鸿蒙示例代码-鸿蒙开发者社区

使用说明

进入应用点击消息列表的图片可对图片进行缩放、拖动查看操作,点击视频可预览视频。

实现思路

预览图片

通过设定手势事件PanGesture触发滑动的手指数、滑动距离以及手势识别的回调事件,实现双击缩放以及双指缩放图片功能。核心代码如下,源码参考ImagePreview.ets

PinchGesture({ fingers: 2, distance: 1 })
            .onActionStart((e) => {
              this.defaultScale = this.activeImage.scale
            })
            .onActionUpdate((e) => {
              let scale = e.scale * this.defaultScale
              if (scale <= 4 && scale >= 1) {
                this.activeImage.offsetX = this.activeImage.offsetX / (this.activeImage.scale - 1) * (scale - 1) || 0
                this.activeImage.offsetY = this.activeImage.offsetY / (this.activeImage.scale - 1) * (scale - 1) || 0
                this.activeImage.scale = scale
              }
              this.disabledSwipe = this.activeImage.scale > 1
            })
            .onActionEnd((e) => {
              this.disabledSwipe = this.activeImage.scale > 1
            })
            .onActionCancel(() => {
              this.disabledSwipe = this.activeImage.scale > 1
            })
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

预览视频

通过VideoController对象控制预览视频的播放和暂停。核心代码如下,源码参考ImagePreview.ets

OverlayNode() {
    Image(this.isPlay ? $r('app.media.ic_play') : $r('app.media.ic_pause'))
      .zIndex(8)
      .width('10%')
      .height('10%')
      .position({ left: '50%', top: '50%' })
      .translate({ x: '-50%', y: '-50%' })
      .visibility(this.progressState[this.indexChange].ifLoad ? Visibility.Visible : Visibility.None)
      .onClick(() => {
        if (this.isPlay) {
          this.controller.start()
        } else {
          this.controller.pause()
        }
        this.isPlay = !this.isPlay
      })
  }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

分类
收藏
回复
举报


回复
    相关推荐