HarmonyOS 指南针实现?

如何实现手机屏幕展示指南针表盘,根据手机设备朝向实时变动指针朝向。

阅读 604
1 个回答

示例参考如下:

import { sensor } from '@kit.SensorServiceKit';

@Entry
@Component
struct Index {
  @State directionPos: object = new Object({ x: 0, y: 0, z: 0 });
  @State angle: number = 0;

  aboutToAppear(): void {
    sensor.on(sensor.SensorId.MAGNETIC_FIELD, (data: sensor.AccelerometerResponse) => {
      this.directionPos['x'] = data.x;
      this.directionPos['y'] = data.y;
      this.angle = -90 + Math.atan2(this.directionPos['x'], this.directionPos['y']) * 180 / Math.PI;
      this.message = this.angle + ""
    }, { interval: 1000 })
  }

  build() {
    Column() {
      Stack() {
        Image($rawfile('OIP.png')).width(300).height(300).rotate({
          angle: this.angle + 90
        })
        Image($rawfile('ic_screenshot_arrowhead.png')).width(48).height(48)
          .rotate({
            angle: this.angle
          })
      }
    }
    .height('100%')
    .width('100%')
  }
}