• Lv0
    粉丝0

积分186 / 贡献0

提问33答案被采纳3文章0

如何锁定设备竖屏,使得窗口不随屏幕旋转

westinyang

沙发 发表于 2023-10-31 11:48:44

如何锁定设备竖屏,使得窗口不随屏幕旋转

// 获取所有的屏幕
let screenClass = null;
screen.getAllScreens((err, data) => {
    if (err.code) {
        console.error('Failed to get all screens. Cause:  ' + JSON.stringify(err));
        return;
    }
    console.info('Succeeded in getting all screens. Data:' + JSON.stringify(data));
    screenClass = data[0];

    // 设置屏幕方向 VERTICAL HORIZONTAL
    try {
        screenClass.setOrientation(screen.Orientation.VERTICAL, (err, data) => {
            if (err.code) {
                console.error('Failed to set the vertical orientation. Code: ' + JSON.stringify(err));
                return;
            }
            console.info('Succeeded in setting the vertical orientation. data: ' + JSON.stringify(data));
        });
    } catch (exception) {
        console.error('Failed to set the vertical orientation. Code: ' + JSON.stringify(exception));
    };
});

AIP详细说明可参考:@ohos.screen (屏幕) (openharmony.cn)

HmD

板凳 发表于 2023-11-8 14:12:16

采用窗口的setPreferredOrientation方法可以实现该效果,将orientation参数设置为window.Orientation.PORTRAIT时,可锁定屏幕为竖屏。

import window from "@ohos.window";
//1.获取窗口实例对象,新建窗口使用createWindow方法,获取已有的窗口使用findWindow方法
let windowClass = null;
let config = {name: "alertWindow", windowType: window.WindowType.TYPE_SYSTEM_ALERT, ctx: this.context};
try {
    let promise = window.createWindow(config);
    promise.then((data)=> {
        windowClass = data;
        console.info('Succeeded in creating the window. Data:' + JSON.stringify(data));
    }).catch((err)=>{
        console.error('Failed to create the Window. Cause:' + JSON.stringify(err));
    });} catch (exception) {
    console.error('Failed to create the window. Cause: ' + JSON.stringify(exception));
}
//2.窗口实例使用setPreferredOrientation方法,设置窗口的显示方向,PROTRAIT为固定竖屏,其他方向可参照参考链接
let orientation = window.Orientation.PORTRAIT;
if (windowClass) {
    windowClass.setPreferredOrientation(orientation, (err) => {
        if (err.code) {
            console.error('Failed to set window orientation. Cause: ' + JSON.stringify(err));
            return;
        }
        console.info('Succeeded in setting window orientation.');
}

Copyright   ©2023  OpenHarmony开发者论坛  京ICP备2020036654号-3 |技术支持 Discuz!

返回顶部