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

介绍

本示例通过 setPreferredOrientation 方法来控制窗口的横竖屏显示,通过设置组件的 rotate 属性来控制组件的横竖屏显示。

实现横竖屏切换源码链接

效果预览

请添加链接描述

使用说明

点击横屏竖屏按钮实现窗口的横竖屏显示切换,点击组件旋转按钮实现组件的横竖屏显示切换。

实现思路

  1. 点击横屏竖屏按钮后调用setPreferredOrientation 方法来控制窗口的横竖屏显示。

    const topWindow = await window.getLastWindow(getContext(this));
    await topWindow.setPreferredOrientation(window.Orientation.LANDSCAPE_INVERTED);
    ...
    const topWindow = await window.getLastWindow(getContext(this));
    await topWindow.setPreferredOrientation(window.Orientation.PORTRAIT);
  2. 点击组件旋转按钮后通过设置组件的 rotate 属性来控制组件的横竖屏显示,同时通过onAreaChange来获取区域变化信息。

    Column() {
      Button($r('app.string.button_rotate'))
     .onClick(() => {
       if (this.angle === 0) {
         this.angle = 90;
         this.newWidth = this.tempWidth;
         this.newHeight = this.tempHeight;
       } else {
         this.angle = 0;
         this.newWidth = this.tempWidth;
         this.newHeight = this.tempHeight;
       }
     });
    }
    .onAreaChange((oldValue: Area, newValue: Area) => {
      this.tempWidth = newValue.height as number;
      this.tempHeight = newValue.width as number;
    })
    .height(this.newHeight)
    .width(this.newWidth)
    .backgroundColor(Color.Blue)
    .rotate({ angle: this.angle });

鸿蒙场景化代码
1 声望0 粉丝