实现横竖屏切换鸿蒙示例代码

鸿蒙场景化示例代码技术工程师
发布于 2025-3-7 15:42
浏览
0收藏

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

介绍

本示例通过 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);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  1. 点击组件旋转按钮后通过设置组件的 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.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

分类
收藏
回复
举报
回复
    相关推荐