1、MainActivity.cs文件
在OnCreate添加
Xamarin.Essentials.Platform.Init(this, bundle);
添加方法
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults){Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);base.OnRequestPermissionsResult(requestCode, permissions, grantResults);}
参考链接 Xamarin.Essentials 入门 - Xamarin | Microsoft Docs
2、在xaml文件添加指南针图片
<Image Source="" Rotation="{Binding Heading}"/>
3、在xaml.cs文件添加
protected override void OnAppearing(){base.OnAppearing();if (Compass.IsMonitoring)return;Compass.ReadingChanged += Compass_ReadingChanged;Compass.Start(SensorSpeed.UI, true);}private void Compass_ReadingChanged(object sender, CompassChangedEventArgs e){Heading = 360 - e.Reading.HeadingMagneticNorth;}protected override void OnDisappearing(){base.OnDisappearing();if (!Compass.IsMonitoring)return;Compass.ReadingChanged -= Compass_ReadingChanged;Compass.Stop();}
图片就会跟随方位旋转
参考链接 Xamarin.Essentials:指南针 - Xamarin | Microsoft Docs