HarmonyOS 如何获取手机屏幕旋转角度?

如题:HarmonyOS 如何获取手机屏幕旋转角度?

阅读 465
1 个回答

获取当前设备旋转角度请参考传感器接口实现:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-sensor-V5

参考demo

import sensor from '@ohos.sensor';
import base from '@ohos.base';

export function onDegree(callback: base.Callback<string>): void {
  sensor.on(sensor.SensorId.GRAVITY, (data: sensor.GravityResponse) => {
    let degree: number = -1;
    let rotation: string = 'INVALID';
    degree = CalDegree(data.x, data.y, data.z)
    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';
    }
    callback(rotation);
  });
}

function CalDegree(x: number, y: number, z: number): number {
  let degree: number = -1;
  // 3 为 有效_增量_角度_阈值_系数
  if ((x * x + y * y) * 3 < z * z) {
    return degree;
  }
  degree = 90 - (Number)(Math.round(Math.atan2(y, -x) / Math.PI * 180));
  return degree >= 0 ? degree % 360 : degree % 360 + 360;
}

@Component
@Entry
struct Index{

  aboutToAppear() {
    let callback = async (rotation: string) => {
      console.log('rotation = ' + rotation )
    }
    try {
      //监听屏幕状态改变
      onDegree(callback);
    } catch (exception) {
    }
  }

  build() {

  }
}

或者参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-display-V5\#displaygetdefaultdisplaysync9

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进