HarmonyOS鸿蒙Next中实现横竖屏切换示例代码
HarmonyOS鸿蒙Next中实现横竖屏切换示例代码
介绍
本示例通过 setPreferredOrientation 方法来控制窗口的横竖屏显示,通过设置组件的 rotate 属性来控制组件的横竖屏显示。
效果预览
使用说明
点击横屏竖屏按钮实现窗口的横竖屏显示切换,点击组件旋转按钮实现组件的横竖屏显示切换。
实现思路
- 点击横屏竖屏按钮后调用 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);
- 点击组件旋转按钮后通过设置组件的 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 });
更多关于HarmonyOS鸿蒙Next中实现横竖屏切换示例代码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS中实现横竖屏切换,可以通过监听设备方向变化来实现。以下是一个简单的示例代码,展示如何在鸿蒙Next中处理横竖屏切换:
import featureAbility from '@ohos.ability.featureAbility';
import window from '@ohos.window';
export default {
onOrientationChange() {
const context = featureAbility.getContext();
window.getTopWindow(context, (err, win) => {
if (err) {
console.error('Failed to get top window.');
return;
}
win.on('orientationChange', (data) => {
if (data === window.Orientation.VERTICAL) {
console.log('当前为竖屏');
} else if (data === window.Orientation.HORIZONTAL) {
console.log('当前为横屏');
}
});
});
}
};
在这个示例中,首先通过featureAbility.getContext()
获取当前上下文,然后通过window.getTopWindow()
获取顶层窗口对象。接着,监听orientationChange
事件,当设备方向发生变化时,根据返回的data
值判断当前是竖屏还是横屏。window.Orientation.VERTICAL
表示竖屏,window.Orientation.HORIZONTAL
表示横屏。
更多关于HarmonyOS鸿蒙Next中实现横竖屏切换示例代码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,可以通过Direction
属性和onConfigurationChange
事件来实现横竖屏切换。以下是一个简单的示例代码:
import { Direction, globalThis, onConfigurationChange } from '@ohos.application';
// 监听屏幕方向变化
onConfigurationChange((config) => {
if (config.direction === Direction.DIRECTION_VERTICAL) {
console.log("当前为竖屏模式");
} else if (config.direction === Direction.DIRECTION_HORIZONTAL) {
console.log("当前为横屏模式");
}
});
// 设置初始屏幕方向
globalThis.configuration.direction = Direction.DIRECTION_VERTICAL;
此代码监听屏幕方向变化,并根据方向打印相应信息。globalThis.configuration.direction
可以设置初始屏幕方向。