나침반 사용

나침반을 사용하여 현재 제목을 확인하는 방법을 알아봅니다.

이 예제에서는 나침반을 입력 디바이스로 사용하는 간단한 앱을 만듭니다. 앱은 자북 또는 진북을 기준으로 현재 방위를 가져올 수 있습니다. 탐색 앱은 나침반을 사용하여 디바이스가 향하고 있는 방향을 확인한 다음 그에 따라 지도 방향을 지정합니다.

Note

이 문서에서는 나침반을 사용하는 방법을 보여 주는 코드에 중점을 둡니다. 나침반 센서에 대한 개요는 센서: 나침반을 참조하세요.

사전 요구 사항

나침반 센서와 그 용도에 대해 잘 알고 있어야 합니다. 센서: 나침반을 참조하세요.

사용 중인 디바이스 또는 에뮬레이터는 나침반을 지원해야 합니다.

예제 코드

using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml.Controls;
using Windows.Devices.Sensors;

namespace DevicesDemo.Pages
{
    public sealed partial class CompassPage : Page
    {
        private Compass? compass;

        public CompassPage()
        {
            InitializeComponent();

            // Get the default compass object.
            compass = Compass.GetDefault(); 

            if (compass != null)
            {
                // Establish the report interval for all scenarios.
                uint minReportInterval = compass.MinimumReportInterval;
                uint reportInterval = minReportInterval > 16 ? minReportInterval : 16;
                compass.ReportInterval = reportInterval;

                // Assign an event handler for the reading-changed event.
                compass.ReadingChanged += Compass_ReadingChanged;
            }
            else
            {
                statusBar.Message = "No compass was found.";
                statusBar.Severity = InfoBarSeverity.Error;
                statusBar.IsOpen = true;
            }
        }

        // This event handler writes the current compass
        // reading to the text blocks on the XAML page.
        private void Compass_ReadingChanged(Compass sender, CompassReadingChangedEventArgs args)
        {
            DispatcherQueue?.TryEnqueue(DispatcherQueuePriority.Normal, () =>
            {
                CompassReading reading = args.Reading;
                txtMagnetic.Text = String.Format("{0,5:0.00}", reading.HeadingMagneticNorth);
                if (reading.HeadingTrueNorth.HasValue)
                    txtNorth.Text = String.Format("{0,5:0.00}", reading.HeadingTrueNorth);
                else
                    txtNorth.Text = "No reading.";
            });
        }
    }
}
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid Margin="24">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="44"/>
            <RowDefinition Height="44"/>
        </Grid.RowDefinitions>
        <TextBlock Text="Magnetic Heading:" Style="{StaticResource LabelTextBlockStyle}"/>
        <TextBlock x:Name="txtMagnetic" Grid.Column="1" Text="---"/>

        <TextBlock Grid.Row="1" Text="True North Heading:" Style="{StaticResource LabelTextBlockStyle}"/>
        <TextBlock x:Name="txtNorth" Grid.Column="1" Grid.Row="1" Text="---"/>
    </Grid>

    <InfoBar x:Name="statusBar" Grid.Row="1"/>
</Grid>

앱이 실행되면 디바이스를 이동하여 나침반 값을 변경할 수 있습니다.

이전 예제에서는 나침반 입력을 앱에 통합하기 위해 작성해야 하는 필수 코드를 보여 줍니다.

센서에 연결

GetDefault 메서드를 호출하여 기본 나침반과의 연결을 설정합니다.

private Compass? compass;
// ...
compass = Compass.GetDefault();

FromIdAsync를 호출하여 DeviceInformation.Id 값에서 Compass 개체를 만들 수도 있습니다. 자세한 내용은 디바이스 열거를 참조하세요.

나침반 센서가 검색되지 않으면 사용자에게 알리도록 상태 메시지가 업데이트됩니다.

보고서 간격 설정

보고서 간격은 페이지의 생성자 내에서 설정됩니다. 이 코드는 디바이스에서 지원하는 최소 간격을 검색하고 요청된 간격인 16밀리초(약 60Hz 새로 고침 속도)와 비교합니다. 지원되는 최소 간격이 요청된 간격보다 큰 경우 코드는 값을 최소값으로 설정합니다. 그렇지 않으면 값을 요청된 간격으로 설정합니다.

uint minReportInterval = compass.MinimumReportInterval;
uint reportInterval = minReportInterval > 16 ? minReportInterval : 16;
compass.ReportInterval = reportInterval;

센서 데이터 읽기

새 나침반 데이터는 ReadingChanged 이벤트 처리기에서 캡처됩니다. 센서 드라이버가 센서에서 새 데이터를 받을 때마다 이 이벤트를 사용하여 값을 앱에 전달합니다. 이 예제에서는 이러한 새 값이 해당 페이지의 XAML에 있는 텍스트 블록에 기록됩니다.

compass.ReadingChanged += Compass_ReadingChanged;
// ...

private void Compass_ReadingChanged(Compass sender, CompassReadingChangedEventArgs args)
{
    DispatcherQueue?.TryEnqueue(DispatcherQueuePriority.Normal, () =>
    {
        CompassReading reading = args.Reading;
        txtMagnetic.Text = String.Format("{0,5:0.00}", reading.HeadingMagneticNorth);
        if (reading.HeadingTrueNorth.HasValue)
            txtNorth.Text = String.Format("{0,5:0.00}", reading.HeadingTrueNorth);
        else
            txtNorth.Text = "No reading.";
    });
}