场景描述
目前很多应用和场景需要用到横竖屏旋转,下面列举一些目前遇到的高频问题:
场景一:我们如何通过传感器自己感知方向,自己设置旋转;(使用sensor感知设备是不关心设备是否启用系统自带的旋转锁定)
场景二:在一个应用内,不同的页面有不同的旋转策略;如:首页仅竖屏,详情页面允许横竖屏切换;
概念说明:
本文的旋转策略是:旋转策略是指当前页面支持的设备旋转方向。
页面方向是:页面方向是手机的页面当前的显示方向。
场景一:
我们如何通过传感器自己感知方向,自己设置旋转;(使用sensor感知设备是不关心设备是否启用系统自带的旋转锁定)
效果图:
关键步骤:
第一步:感知方向;使用sensor感知设备的真实朝向。
// 1 原始数据(3维度)
sensor.on(sensor.SensorId.GRAVITY, (data: sensor.GravityResponse) => {
let degree: number = -1;
let rotation: string = 'INVALID';
// 2 将三维的角度变二维
degree = CalDegree(data.x, data.y, data.z)
// 3 将角度转化到方向
if (degree >= 0 && (degree <= 30 || degree >= 330)) {
rotation = "ROTATION_0";
} else if (degree >= 60 && degree <= 120) { // Use ROTATION_90 when degree range is [60, 120]
rotation = "ROTATION_90";
} else if (degree >= 150 && degree <= 210) { // Use ROTATION_180 when degree range is [150, 210]
rotation = "ROTATION_180";
} else if (degree >= 240 && degree <= 300) { // Use ROTATION_270 when degree range is [240, 300]
rotation = "ROTATION_270";
}
第二步:设置旋转;
相关接口:setPreferredOrientation;设置窗口的显示方向属性
indow(getContext(this)).then((data) => {
data.setPreferredOrientation(window.Orientation.LANDSCAPE_INVERTED)
})
设置方向:
相关接口:
调用窗口的Orientation设置方向即可,具体的设置窗口的显示方向,属性设置参考下表;
UNSPECIFIED | 表示未定义方向模式,由系统判定。 |
---|---|
PORTRAIT | 表示竖屏显示模式。 |
LANDSCAPE | 表示横屏显示模式。 |