Simple device orientation sensor windows 10 что это

Датчик ориентации экрана в WinRT

В этой и следующих статьях основное внимание уделяется информации, получаемой от классов SimpleOrientationSensor, Accelerometer, Compass, Inclinometer, OrientationSensor и Geolocator. К сожалению, мне придется пропустить реже используемые классы LightSensor и Gyrometer для получения информации об освещенности и угловой скорости компьютера.

Чтобы получить максимум пользы от этого материала, следует взять компьютер, на котором запущены программы-примеры, и переместить его в пространстве. Если ваша машина разработки с системой Windows 8 прикована к столу (как и моя), возьмите планшет — например, Microsoft Surface — и разверните программы на нем в удаленном режиме.

Ориентация

Простейшим из всех классов датчиков является класс SimpleOrientationSensor; он дает программе примерное представление об ориентации в трехмерном пространстве, но без особых подробностей. Для получения экземпляра SimpleOrientationSensor вызывается статический метод:

Эта операция выполняется в приложении только один раз, так что код может выполняться в определении поля для предоставления доступа к этому объекту в классе.

Если метод GetDefault() возвращает null, компьютер не располагает средствами для определения своей ориентации.

Значение, описывающее текущую ориентацию, может быть в любой момент времени получено от объекта SimpleOrientationSensor:

Перечисление SimpleOrientation состоит из шести значений:

Именно из-за ограниченности этой информации класс SimpleOrientationSensor называется «простым» (simple).

Также программа может получать оповещения о событиях при изменении ориентации. Назначьте обработчик для события OrientationChanged:

Событие инициируется только при изменении ориентации, чего не произойдет, если компьютер остается относительно неподвижным. Если для работы программы необходимо исходное значение, вызовите метод GetCurrentOrientation после назначения обработчика события.

Обработчик события выполняется в собственном потоке, поэтому для взаимодействия с потоком пользовательского интерфейса необходимо использовать объект CoreDispatcher:

Аргумент события с очень длинным именем содержит свойство Orientation перечислимого типа SimpleOrientation и свойство Timestamp типа DateTimeOffset. Резонно спросить: а разве мы не располагаем информацией об ориентации устройства? Разве она не предоставляется пространством имен Windows.Graphics.Display? Разве класс DisplayProperties и его статические свойства NativeOrientation и CurrentOrientation, а также событие OrientationChanged не предоставляют информацию об ориентации? Напомню, что эти два статических свойства возвращают значения перечислимого типа DisplayOrientations: Landscape, Portrait, LandscapeFlipped, PortraitFlipped.

Классы SimpleOrientationSensor и DisplayProperties безусловно связаны, но важно понять суть этой связи: класс SimpleOrientationSensor описывает ориентацию компьютера в трехмерном пространстве. Свойство DisplayProperties.CurrentOrientation описывает, каким образом Windows компенсирует ориентацию компьютера посредством автоматического изменения ориентации окна вашей программы. Иначе говоря, SimpleOrientationSensor сообщает информацию об ориентации оборудования, a DisplayProperties.CurrentOrientation — информацию об изменении ориентации программы, которая произошла в ответ на изменение ориентации оборудования.

Проект OrientationAndOrientation поможет вам различать два вида ориентации. Файл XAML определяет несколько элементов TextBlock для вывода меток и данных:

Файл фонового кода определяет два метода с единственной целью — заданием двух элементов TextBlock во втором столбце Grid. Эти два метода вызываются как из конструктора для задания исходных значений, так и из двух обработчиков событий:

Обратите внимание: экземпляр SimpleOrientationSensor создается как поле, но конструктор проверяет возможное значение null перед обращением к объекту.

Значения датчика ориентации (SimpleOrientationSensor) и устройства (DisplayProperties.CurrentOrientation) при альбомной ориентации

SimpleOrientationSensorDisplayProperties.CurrentOrientation
NotRotatedLandscape
Rotated270DegreesCounterclockwisePortrait
Rotated180DegreesCounterclockwiseLandscapeFlipped
Rotated90DegreesCounterclockwisePortraitFlipped

SimpleOrientationSensor также возвращает значения Faceup и Facedown, не имеющие аналогов в перечислении DisplayOrientations.

Хотя приведенная таблица приблизительно верна для планшета с основной альбомной ориентацией, у мобильного устройства с основной книжной ориентацией соответствия будут выглядеть так:

Источник

Simple Orientation Sensor Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Represents a simple orientation sensor.

For an example implementation, see the simple orientation sensor sample.

This sensor detects the current quadrant orientation of the specified device as well as its face-up or face-down status.

Windows requirements

Remarks

The following example demonstrates how a UWP app built with XAML and C# uses the GetDefault method to establish a connection to a simple orientation sensor. If no simple orientation sensor is found, the method will return a null value.

The following example demonstrates how a UWP app built with XAML registers a OrientationChanged event handler.

The following example contains the XAML code for the event handler which writes the orientation readings to the application’s form.

Version history

Windows versionSDK versionValue added
180917763FromIdAsync
180917763GetDeviceSelector

Properties

Gets the device identifier used in the SimpleOrientationSensor.FromIdAsync method.

Gets or sets the transformation that needs to be applied to sensor data. Transformations to be applied are tied to the display orientation with which to align the sensor data.

Methods

Asynchronously retrieves a SimpleOrientationSensor object based on the specified device identifier.

Gets the default simple orientation sensor.

Gets the default simple orientation sensor.

Retrieves an Advanced Query Syntax (AQS) string used to enumerate the available SimpleOrientationSensor devices.

Events

Occurs each time the simple orientation sensor reports a new sensor reading

Источник

Использование датчика положения в пространстве

Важные API

Примеры

Узнайте, как использовать датчики положения в пространстве для определения ориентации устройства.

Пространство имен Windows.Devices.Sensors включает два типа API датчиков положения в пространстве: OrientationSensor и SimpleOrientation. Хотя оба этих датчика – датчики положения в пространстве, данный термин многозначен, и датчики используются для совершенно разных целей. Но так как оба этих датчика – датчики положения в пространстве, оба они описаны в этой статье.

API OrientationSensor используется трехмерными приложениями, в которых есть кватернион и матрица поворота. Объект Quaternion можно легко понять как поворот точки [x, y, z] о произвольной оси (отличие от матрицы вращения, которая представляет повороты вокруг трех осей). Математика кватернионов довольно экзотична, так как использует геометрические свойства комплексных чисел и математические свойства мнимых чисел, но работать с ними просто, и их поддерживают различные программные платформы, например DirectX. Сложное трехмерное приложение может использовать датчик положения в пространстве для выравнивания перспективы пользователя. Этот датчик группирует данные от акселерометра, гирометра и компаса.

API SimpleOrientation используется, чтобы определять текущую ориентацию устройства относительно таких определений, как книжная вверх, книжная вниз, альбомная влево и альбомная вправо. Он также может обнаружить поворот устройства лицевой стороной вниз или вверх. Вместо свойств типа «книжная вверх или «альбомная влево» этот датчик возвращает значение поворота: Not rotated (Не повернуто), Rotated90DegreesCounterclockwise (Повернуто на 90 градусов против часовой стрелки) и т. д. В следующей таблице представлены свойства ориентации и соответствующие им показания датчика.

OrientationСоответствующие показания датчика
Книжная вверхNotRotated
Альбомная влевоRotated90DegreesCounterclockwise
Книжная внизRotated180DegreesCounterclockwise
Альбомная вправоRotated270DegreesCounterclockwise

Предварительные требования

Вы должны быть знакомы с языком XAML, Microsoft Visual C# и событиями.

Используемые вами устройство или эмулятор должны поддерживать датчик положения в пространстве.

Создание приложения OrientationSensor

Данный раздел состоит из двух подразделов. В первом подразделе описаны необходимые этапы создания приложения ориентации с нуля. В следующем подразделе описано приложение, которое вы только что создали.

Инструкции

Для создания нового проекта выберите Пустое приложение (универсальное приложение Windows) из шаблонов проектов Visual C#.

Откройте файл проекта MainPage.xaml.cs и замените существующий код следующим.

После запуска приложения можно изменить значения ориентации, перемещая устройство или используя средства эмулятора.

Объяснение

Из предыдущего примера видно, какой небольшой объем кода требуется написать, чтобы включить в ваше приложение обработку входных данных датчика положения в пространстве.

Приложение устанавливает связь с датчиком положения в пространстве по умолчанию в методе MainPage.

Приложение устанавливает интервал передачи данных в методе MainPage. Этот код позволяет получить значение минимально допустимого для данного устройства интервала и сравнить его с требуемым интервалом в 16 миллисекунд (что приблизительно соответствует частоте обновления 60 Гц). Если минимально допустимый интервал больше требуемого, то код задает значение интервала, равное минимальному. В противном случае задается значение интервала, равное необходимому.

Новые данные от датчика принимаются в методе ReadingChanged. Каждый раз, когда драйвер датчика получает от датчика новые данные, он передает их вашему приложению с помощью этого обработчика событий. Приложение регистрирует этот обработчик событий в следующей строке:

Новые значения записываются в элементы TextBlock в XAML-коде проекта.

Создание простого приложения ориентации

Данный раздел состоит из двух подразделов. В первом подразделе описаны необходимые этапы создания простого приложения ориентации с нуля. В следующем подразделе описано приложение, которое вы только что создали.

Инструкции

Для создания нового проекта выберите Пустое приложение (универсальное приложение Windows) из шаблонов проектов Visual C#.

Откройте файл проекта MainPage.xaml.cs и замените существующий код следующим.

После запуска приложения можно изменить значения ориентации, перемещая устройство или используя средства эмулятора.

Объяснение

Из предыдущего примера видно, какой небольшой объем кода требуется написать, чтобы включить в ваше приложение обработку входных данных простого датчика положения в пространстве.

Приложение устанавливает связь с датчиком по умолчанию в методе MainPage.

Новые данные от датчика принимаются в методе OrientationChanged. Каждый раз, когда драйвер датчика получает от датчика новые данные, он передает их вашему приложению с помощью этого обработчика событий. Приложение регистрирует этот обработчик событий в следующей строке:

Эти новые значения записываются в элемент TextBlock в XAML-коде проекта.

Источник

Microsoft Surface tablet

I always disconnected my type cover and enabled the Tablet mode on my Surface Pro 4, so that I can easily read PDF and Office Word documents. However, after my tablet installed Windows 10 anniversary update, the screen rotate button had completely disappeared from the action center and the related options was missing in Display settings. Now I am stuck with no rotation charm and lost the ability to auto rotate.

How to fix Auto Rotation Lock Option missing/lost after Windows 10 anniversary update
The Hardware and Devices troubleshooter can help you updated the related HID sensors driver
* Open Control Panel > Hardware and Sound > Configure a device, check Apply repairs automatically box, click Next to scan for updated drivers, choose the ones you want to fix and click on Next to begin processing.
* After it is finished, make a rebooting and rotation come back.
* Or you can also search for a driver update in device manager manually.
Make change with key of regedit and that works for me
* Press Win + R from keyboard, type regedit into Run box, and hit Enter.
* Within the left pane of Registry Editor, go to the tree below:

* In its right pane, double click on the SensorPresent string, and change its value data from 0 to 1, and click OK button.
* Close regedit editor and reboot the system to check if it is working normally.
Another way:
* If your device have connected with keyboard, just remove it.
* Open the Setting app, go to System > Display, click the drop down menu in “Orientation” section to choose the Portrait options, and click Keep changes option.
* Restart your tablet or computer. Then you should find the the Rotation Lock icon and get the auto-rotate function back.

Источник

Use the orientation sensor

Important APIs

Samples

Learn how to use the orientation sensors to determine the device orientation.

There are two different types of orientation sensor APIs included in the Windows.Devices.Sensors namespace: OrientationSensor and SimpleOrientation. While both of these sensors are orientation sensors, that term is overloaded and they are used for very different purposes. However, since both are orientation sensors, they are both covered in this article.

The OrientationSensor API is used for 3-D apps two obtain a quaternion and a rotation matrix. A quaternion can be most easily understood as a rotation of a point [x,y,z] about an arbitrary axis (contrasted with a rotation matrix, which represents rotations around three axes). The mathematics behind quaternions is fairly exotic in that it involves the geometric properties of complex numbers and mathematical properties of imaginary numbers, but working with them is simple, and frameworks like DirectX support them. A complex 3-D app can use the Orientation sensor to adjust the user’s perspective. This sensor combines input from the accelerometer, gyrometer, and compass.

The SimpleOrientation API is used to determine the current device orientation in terms of definitions like portrait up, portrait down, landscape left, and landscape right. It can also detect if a device is face-up or face-down. Rather than returning properties like «portrait up» or «landscape left», this sensor returns a rotation value: «Not rotated», «Rotated90DegreesCounterclockwise», and so on. The following table maps common orientation properties to the corresponding sensor reading.

OrientationCorresponding sensor reading
Portrait UpNotRotated
Landscape LeftRotated90DegreesCounterclockwise
Portrait DownRotated180DegreesCounterclockwise
Landscape RightRotated270DegreesCounterclockwise

Prerequisites

You should be familiar with Extensible Application Markup Language (XAML), Microsoft VisualВ C#, and events.

The device or emulator that you’re using must support a orientation sensor.

Create an OrientationSensor app

This section is divided into two subsections. The first subsection will take you through the steps necessary to create an orientation application from scratch. The following subsection explains the app you have just created.

Instructions

Create a new project, choosing a Blank App (Universal Windows) from the Visual C# project templates.

Open your project’s MainPage.xaml.cs file and replace the existing code with the following.

Once the app is running, you can change the orientation by moving the device or using the emulator tools.

Explanation

The previous example demonstrates how little code you’ll need to write in order to integrate orientation-sensor input in your app.

The app establishes a connection with the default orientation sensor in the MainPage method.

The app establishes the report interval within the MainPage method. This code retrieves the minimum interval supported by the device and compares it to a requested interval of 16 milliseconds (which approximates a 60-Hz refresh rate). If the minimum supported interval is greater than the requested interval, the code sets the value to the minimum. Otherwise, it sets the value to the requested interval.

The new sensor data is captured in the ReadingChanged method. Each time the sensor driver receives new data from the sensor, it passes the values to your app using this event handler. The app registers this event handler on the following line.

These new values are written to the TextBlocks found in the project’s XAML.

Create a SimpleOrientation app

This section is divided into two subsections. The first subsection will take you through the steps necessary to create a simple orientation application from scratch. The following subsection explains the app you have just created.

Instructions

Create a new project, choosing a Blank App (Universal Windows) from the Visual C# project templates.

Open your project’s MainPage.xaml.cs file and replace the existing code with the following.

Once the app is running, you can change the orientation by moving the device or using the emulator tools.

Explanation

The previous example demonstrates how little code you’ll need to write in order to integrate simple-orientation sensor input in your app.

The app establishes a connection with the default sensor in the MainPage method.

The new sensor data is captured in the OrientationChanged method. Each time the sensor driver receives new data from the sensor, it passes the values to your app using this event handler. The app registers this event handler on the following line.

These new values are written to a TextBlock found in the project’s XAML.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *