Nota:
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
Obtenga información sobre cómo usar los sensores de orientación para determinar la orientación del dispositivo.
En este ejemplo se crea una aplicación sencilla que se basa en un sensor de orientación como dispositivo de entrada. Un sensor de orientación es uno de los varios tipos de sensores ambientales que permiten a las aplicaciones responder a los cambios en la orientación del dispositivo.
- API importantes:Windows.Devices.Sensors, OrientationSensor, SimpleOrientationSensor
Note
Este artículo se centra en el código que muestra cómo usar un sensor de orientación. Para obtener información general sobre los sensores de orientación, consulte Sensores: Sensor de orientación.
Prerequisites
Debe estar familiarizado con el sensor de orientación y sus usos. Consulte Sensores: Sensor de orientación.
El dispositivo que usa debe admitir un sensor de orientación.
Tipos de sensor de orientación
Hay dos tipos diferentes de API de sensor de orientación incluidas en el Windows. Devices.Sensors espacio de nombres: OrientationSensor y SimpleOrientation. Aunque ambos sensores son sensores de orientación, ese término está sobrecargado y se usan con fines muy diferentes. Sin embargo, dado que ambos son sensores de orientación, ambos se tratan en este artículo.
La API OrientationSensor se utiliza en aplicaciones 3D para obtener un cuaternión y una matriz de rotación. Un cuaternión se puede entender más fácilmente como un giro de un punto [x,y,z] sobre un eje arbitrario (contrastado con una matriz de rotación, que representa rotaciones alrededor de tres ejes). Las matemáticas detrás de cuaterniones son bastante exóticas en que implica las propiedades geométricas de números complejos y propiedades matemáticas de números imaginarios, pero trabajar con ellos es simple, y marcos como DirectX los admiten. Una aplicación compleja 3D puede usar el sensor Orientation para ajustar la perspectiva del usuario. Este sensor combina la entrada del acelerómetro, el girómetro y la brújula.
La API SimpleOrientationSensor se utiliza para determinar la orientación física actual del dispositivo según definiciones como vertical normal, vertical invertida, horizontal hacia la izquierda y horizontal hacia la derecha. También puede detectar si un dispositivo está cara arriba o abajo. En lugar de devolver valores como "vertical hacia arriba" o "horizontal hacia la izquierda", este sensor devuelve un valor de rotación: "Sin rotación", "Girado 90 grados en sentido antihorario", y así sucesivamente. En la tabla siguiente se asignan las propiedades de orientación comunes a la lectura del sensor correspondiente.
| Orientación | Lectura del sensor correspondiente |
|---|---|
| Vertical hacia arriba | Sin rotación |
| Horizontal izquierdo | Girado 90 grados en sentido antihorario |
| Vertical hacia abajo | Girado 180 grados en sentido antihorario |
| Horizontal derecha | Girado 270 grados en sentido antihorario |
Código de ejemplo: sensor de orientación
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml.Controls;
using Windows.Devices.Sensors;
namespace DevicesDemo.Pages
{
public sealed partial class OrientationSensorPage : Page
{
private OrientationSensor? orientationSensor;
public OrientationSensorPage()
{
InitializeComponent();
// Get the default orientation sensor object.
orientationSensor = OrientationSensor.GetDefault();
if (orientationSensor != null)
{
// Establish the report interval.
uint minReportInterval = orientationSensor.MinimumReportInterval;
uint reportInterval = minReportInterval > 16 ? minReportInterval : 16;
orientationSensor.ReportInterval = reportInterval;
// Assign an event handler for the reading-changed event.
orientationSensor.ReadingChanged += OrientationSensor_ReadingChanged;
}
else
{
statusBar.Message = "No orientation sensor was found.";
statusBar.Severity = InfoBarSeverity.Error;
statusBar.IsOpen = true;
}
}
// This event handler writes the current orientation
// reading to the text blocks on the XAML page.
private void OrientationSensor_ReadingChanged(OrientationSensor sender, OrientationSensorReadingChangedEventArgs args)
{
DispatcherQueue?.TryEnqueue(DispatcherQueuePriority.Normal, () =>
{
OrientationSensorReading reading = args.Reading;
// Quaternion values
txtQuaternionX.Text = String.Format("{0,8:0.00000}", reading.Quaternion.X);
txtQuaternionY.Text = String.Format("{0,8:0.00000}", reading.Quaternion.Y);
txtQuaternionZ.Text = String.Format("{0,8:0.00000}", reading.Quaternion.Z);
txtQuaternionW.Text = String.Format("{0,8:0.00000}", reading.Quaternion.W);
// Rotation Matrix values
txtM11.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M11);
txtM12.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M12);
txtM13.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M13);
txtM21.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M21);
txtM22.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M22);
txtM23.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M23);
txtM31.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M31);
txtM32.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M32);
txtM33.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M33);
});
}
}
}
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid Margin="24">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto" MinWidth="66"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto" MinWidth="66"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto" MinWidth="66"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="44"/>
<RowDefinition Height="44"/>
<RowDefinition Height="44"/>
</Grid.RowDefinitions>
<TextBlock Text="M11:" Style="{StaticResource LabelTextBlockStyle}"/>
<TextBlock x:Name="txtM11" Grid.Column="1" Text="---"/>
<TextBlock Text="M12:" Grid.Row="1" Style="{StaticResource LabelTextBlockStyle}"/>
<TextBlock x:Name="txtM12" Grid.Column="1" Grid.Row="1" Text="---"/>
<TextBlock Text="M13:" Grid.Row="2" Style="{StaticResource LabelTextBlockStyle}"/>
<TextBlock x:Name="txtM13" Grid.Column="1" Grid.Row="2" Text="---"/>
<TextBlock Text="M21:" Grid.Column="2" Grid.Row="0" Style="{StaticResource LabelTextBlockStyle}"/>
<TextBlock x:Name="txtM21" Grid.Column="3" Grid.Row="0" Text="---"/>
<TextBlock Text="M22:" Grid.Column="2" Grid.Row="1" Style="{StaticResource LabelTextBlockStyle}"/>
<TextBlock x:Name="txtM22" Grid.Column="3" Grid.Row="1" Text="---"/>
<TextBlock Text="M23:" Grid.Column="2" Grid.Row="2" Style="{StaticResource LabelTextBlockStyle}"/>
<TextBlock x:Name="txtM23" Grid.Column="3" Grid.Row="2" Text="---"/>
<TextBlock Text="M31:" Grid.Column="4" Grid.Row="0" Style="{StaticResource LabelTextBlockStyle}"/>
<TextBlock x:Name="txtM31" Grid.Column="5" Grid.Row="0" Text="---"/>
<TextBlock Text="M32:" Grid.Column="4" Grid.Row="1" Style="{StaticResource LabelTextBlockStyle}"/>
<TextBlock x:Name="txtM32" Grid.Column="5" Grid.Row="1" Text="---"/>
<TextBlock Text="M33:" Grid.Column="4" Grid.Row="2" Style="{StaticResource LabelTextBlockStyle}"/>
<TextBlock x:Name="txtM33" Grid.Column="5" Grid.Row="2" Text="---"/>
</Grid>
<Grid Margin="24" Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="44"/>
<RowDefinition Height="44"/>
<RowDefinition Height="44"/>
<RowDefinition Height="44"/>
</Grid.RowDefinitions>
<TextBlock Text="Quaternion X:" Style="{StaticResource LabelTextBlockStyle}"/>
<TextBlock x:Name="txtQuaternionX" Grid.Column="1" Grid.Row="0" Text="---"/>
<TextBlock Text="Quaternion Y:" Grid.Row="1" Style="{StaticResource LabelTextBlockStyle}"/>
<TextBlock x:Name="txtQuaternionY" Grid.Column="1" Grid.Row="1" Text="---"/>
<TextBlock Text="Quaternion Z:" Grid.Row="2" Style="{StaticResource LabelTextBlockStyle}"/>
<TextBlock x:Name="txtQuaternionZ" Grid.Column="1" Grid.Row="2" Text="---"/>
<TextBlock Text="Quaternion W:" Grid.Row="3" Style="{StaticResource LabelTextBlockStyle}"/>
<TextBlock x:Name="txtQuaternionW" Grid.Column="1" Grid.Row="3" Text="---"/>
</Grid>
<InfoBar x:Name="statusBar" Grid.Row="2"/>
</Grid>
Cuando se ejecuta la aplicación, puedes cambiar los valores de orientación moviendo el dispositivo.
En el ejemplo anterior se muestra el código esencial que debe escribir para integrar la entrada del sensor de orientación en la aplicación.
Conexión al sensor
Llame al método GetDefault para establecer una conexión con el sensor de orientación predeterminado.
private OrientationSensor? orientationSensor;
// ...
orientationSensor = OrientationSensor.GetDefault();
También puede llamar a FromIdAsync para crear un objetoOrientationSensor desde un valor DeviceInformation.Id. Para obtener más información, consulta Enumerar dispositivos.
Si no se detecta ningún sensor de sensor de orientación, el mensaje de estado se actualiza para informar al usuario.
Establecimiento del intervalo de informe
El intervalo de informe se establece dentro del constructor de la página. Este código recupera el intervalo mínimo admitido por el dispositivo y lo compara con un intervalo solicitado de 16 milisegundos (que aproxima una frecuencia de actualización de 60 Hz). Si el intervalo mínimo admitido es mayor que el intervalo solicitado, el código establece el valor en el mínimo. De lo contrario, establece el valor en el intervalo solicitado.
uint minReportInterval = orientationSensor.MinimumReportInterval;
uint reportInterval = minReportInterval > 16 ? minReportInterval : 16;
orientationSensor.ReportInterval = reportInterval;
Leer datos del sensor
Los nuevos datos del sensor de orientación se capturan en el controlador de eventos ReadingChanged . Cada vez que el controlador del sensor recibe nuevos datos del sensor, pasa los valores a la aplicación mediante este evento. En este ejemplo, estos nuevos valores se escriben en los bloques de texto que se encuentran en el XAML de la página correspondiente.
orientationSensor.ReadingChanged += OrientationSensor_ReadingChanged;
// ...
private void OrientationSensor_ReadingChanged(OrientationSensor sender, OrientationSensorReadingChangedEventArgs args)
{
DispatcherQueue?.TryEnqueue(DispatcherQueuePriority.Normal, () =>
{
OrientationSensorReading reading = args.Reading;
// Quaternion values
txtQuaternionX.Text = String.Format("{0,8:0.00000}", reading.Quaternion.X);
txtQuaternionY.Text = String.Format("{0,8:0.00000}", reading.Quaternion.Y);
txtQuaternionZ.Text = String.Format("{0,8:0.00000}", reading.Quaternion.Z);
txtQuaternionW.Text = String.Format("{0,8:0.00000}", reading.Quaternion.W);
// Rotation Matrix values
txtM11.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M11);
txtM12.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M12);
txtM13.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M13);
txtM21.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M21);
txtM22.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M22);
txtM23.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M23);
txtM31.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M31);
txtM32.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M32);
txtM33.Text = String.Format("{0,8:0.00000}", reading.RotationMatrix.M33);
});
}
Código de ejemplo: sensor de orientación simple
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml.Controls;
using Windows.Devices.Sensors;
namespace DevicesDemo.Pages
{
public sealed partial class SimpleOrientationPage : Page
{
private SimpleOrientationSensor? simpleOrientationSensor;
public SimpleOrientationPage()
{
InitializeComponent();
// Get the default simple orientation sensor object.
simpleOrientationSensor = SimpleOrientationSensor.GetDefault();
// Assign an event handler.
if (simpleOrientationSensor != null)
{
// Assign an event handler for the reading-changed event.
simpleOrientationSensor.OrientationChanged
+= SimpleOrientationSensor_OrientationChanged;
}
else
{
statusBar.Message = "No simple orientation sensor was found.";
statusBar.Severity = InfoBarSeverity.Error;
statusBar.IsOpen = true;
}
}
// This event handler writes the current simple orientation
// reading to the text block on the XAML page.
private void SimpleOrientationSensor_OrientationChanged(SimpleOrientationSensor sender,
SimpleOrientationSensorOrientationChangedEventArgs args)
{
DispatcherQueue.TryEnqueue(DispatcherQueuePriority.Normal, () =>
{
switch (args.Orientation)
{
case SimpleOrientation.NotRotated:
txtOrientation.Text = "Not Rotated";
break;
case SimpleOrientation.Rotated90DegreesCounterclockwise:
txtOrientation.Text = "Rotated 90 Degrees Counterclockwise";
break;
case SimpleOrientation.Rotated180DegreesCounterclockwise:
txtOrientation.Text = "Rotated 180 Degrees Counterclockwise";
break;
case SimpleOrientation.Rotated270DegreesCounterclockwise:
txtOrientation.Text = "Rotated 270 Degrees Counterclockwise";
break;
case SimpleOrientation.Faceup:
txtOrientation.Text = "Faceup";
break;
case SimpleOrientation.Facedown:
txtOrientation.Text = "Facedown";
break;
default:
txtOrientation.Text = "Unknown orientation";
break;
}
});
}
}
}
<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"/>
</Grid.RowDefinitions>
<TextBlock Text="Orientation:" Style="{StaticResource LabelTextBlockStyle}"/>
<TextBlock x:Name="txtOrientation" Grid.Column="1" Text="---"/>
</Grid>
<InfoBar x:Name="statusBar" Grid.Row="1"/>
</Grid>
Cuando se ejecuta la aplicación, puedes cambiar los valores de orientación moviendo el dispositivo.
En el ejemplo anterior se muestra el código esencial que debe escribir para integrar la entrada del sensor de orientación simple en la aplicación.
Conexión al sensor de orientación simple
Llame al método GetDefault para establecer una conexión con el sensor de orientación predeterminado.
private SimpleOrientationSensor? simpleOrientationSensor;
// ...
simpleOrientationSensor = SimpleOrientationSensor.GetDefault();
También puede llamar a FromIdAsync para crear un SimpleOrientationSensor a partir de un valor DeviceInformation.Id. Para obtener más información, consulta Enumerar dispositivos.
Si no se detecta ningún sensor de sensor de orientación simple, el mensaje de estado se actualiza para informar al usuario.
Lee los datos básicos del sensor de orientación.
Los nuevos datos del sensor de orientación simple se capturan en el controlador de eventos OrientationChanged . Cada vez que el controlador del sensor recibe nuevos datos del sensor, pasa los valores a la aplicación mediante este evento. En este ejemplo, estos nuevos valores se escriben en el bloque de texto que se encuentra en el XAML de la página correspondiente.
simpleOrientationSensor.OrientationChanged
+= SimpleOrientationSensor_OrientationChanged;
// ...
private void SimpleOrientationSensor_OrientationChanged(SimpleOrientationSensor sender,
SimpleOrientationSensorOrientationChangedEventArgs args)
{
DispatcherQueue.TryEnqueue(DispatcherQueuePriority.Normal, () =>
{
switch (args.Orientation)
{
case SimpleOrientation.NotRotated:
txtOrientation.Text = "Not Rotated";
break;
case SimpleOrientation.Rotated90DegreesCounterclockwise:
txtOrientation.Text = "Rotated 90 Degrees Counterclockwise";
break;
case SimpleOrientation.Rotated180DegreesCounterclockwise:
txtOrientation.Text = "Rotated 180 Degrees Counterclockwise";
break;
case SimpleOrientation.Rotated270DegreesCounterclockwise:
txtOrientation.Text = "Rotated 270 Degrees Counterclockwise";
break;
case SimpleOrientation.Faceup:
txtOrientation.Text = "Faceup";
break;
case SimpleOrientation.Facedown:
txtOrientation.Text = "Facedown";
break;
default:
txtOrientation.Text = "Unknown orientation";
break;
}
});
}
Como alternativa al OrientationChanged evento, puede tomar una lectura única de la orientación actual llamando al método GetCurrentOrientation .