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

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

介绍

本示例通过 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. 点击组件旋转按钮后通过设置组件的 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 });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值