HarmonyOS Next视频播放场景如何适配横竖屏切换?

阅读 563
1 个回答

对应视频播放这类应用,属于只有播放窗口需要进行横竖屏,所以只需要对视频播放的组件内容进行横屏并进入全屏,所以可以利用UI状态更新的特点,来让播窗变为全屏,将播窗的尺寸定义为@State状态,并设置到Xcomponent组件上。

@State xComponentWidth: number = px2vp(display.getDefaultDisplaySync().width);
@State xComponentHeight: number = px2vp(display.getDefaultDisplaySync().width * this.aspect);

将状态变量与播窗绑定。

XComponent({ id: 'video_player_id', type: XComponentType.SURFACE, controller: this.xComponentController })
  .onLoad(() => {
    // ...
  })
  .width(this.xComponentWidth)
  .height(this.xComponentHeight)

并且在之前监听窗口变化的回调中,对XComponentWidth和XComponentHeight进行动态修改,完成窗口变化时横屏和竖屏的视频窗口布局。需要注意的是,在横屏时,视频播放的宽高应该和窗口的宽高一样,并且需要进入全屏状态。而竖屏时,视频播放的宽应该等于窗口的宽,但是高度应该是按照播窗比例乘以窗口的宽进行设置,并退出全屏状态。
具体实现如下,进入视频详情页面内需要监听窗口尺寸的变化,并根据当前状态,实现对横竖屏状态的监听,根据状态变化修改对应XComponent的宽高,实现全屏或者隐藏状态栏和导航条的逻辑。

this.windowClass.on('windowSizeChange', (size) => {

  let viewWidth = px2vp(size.width);
  let viewHeight = px2vp(size.height);

  if (viewWidth > viewHeight) {
    // 实现横屏逻辑
    if (display.getFoldStatus() === 1 || display.getFoldStatus() == 3) {
      this.xComponentHeight = viewWidth * this.aspect;
      this.xComponentWidth = viewWidth;
    } else {
      this.xComponentWidth = viewHeight / this.aspect;
      this.xComponentHeight = viewHeight;
      this.isLandscape = true;
    }
    this.windowClass.setSpecificSystemBarEnabled('navigationIndicator', false); // hide bottom navigation bar
  } else {
    // 实现横屏逻辑
    this.xComponentHeight = viewWidth * this.aspect;
    this.xComponentWidth = viewWidth;

    this.windowClass.setSpecificSystemBarEnabled('navigationIndicator', true); // show bottom navigation bar
    this.isLandscape = false;
  }
});

本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进