HarmonyOS 旋转设备获取设备方向问题?

旋转设备时候使用传感器sensor返回的alpha值来设备方向,发现在设备按x或者y方向旋转会导致alpha值变动导致方向判断错误。代码如下:

sensor.on(sensor.SensorId.ORIENTATION, (data: sensor.OrientationResponse) => {
  let orient: number = (Math.floor((data.alpha) / 90) * 90) % 360
  console.info(TAG, 'sensor orientation = ' + data.alpha + ', orient = ' + orient)
});

该使用方式来获取设备方向是否正确呢?

阅读 480
1 个回答

可以使用重力传感器判断设备朝向,参考demo:

import sensor from '@ohos.sensor';
import base from '@ohos.base';
import { data } from '@kit.TelephonyKit';

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)
    console.log(JSON.stringify(degree))
    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;
}

@Entry
@Component
struct ss {
  build() {
    Column(){
      Button('获取手机设备朝向').onClick(()=>{
        onDegree((data)=> {
          console.log(data);
        })
      })
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏