简体   繁体   English

在Cordova中检测设备方向

[英]Detecting device orientation in cordova

Is there a way to detect physical device orientation in Cordova by accessing accelerometer, compass, or others? 是否可以通过使用加速度计,指南针或其他工具来检测Cordova中物理设备的方向?

I'd like to detect if a device is either sideways (ie landscape) or upright (ie portrait). 我想检测设备是侧身(即风景)还是直立(即肖像)。 Other than: cordova detecting orientation change I won't be able to utilise orientation via window.orientation because it fails in case a user has locked their orientation. 除了: cordova检测方向改变,我将无法通过window.orientation使用方向,因为如果用户锁定了他们的方向,它将失败。

I don't need to know the mode that user is in. Just need to know if the device is sideways or upright. 我不需要知道用户所处的模式。只需要知道设备是侧面还是竖直即可。

I found a blog entry that describes how device orientation can be read from accelerometer despite a locked device orientation . 我找到了一个博客条目,描述了尽管设备方向已锁定,但如何从加速度计读取设备方向

The relevant code snippet is provided in Objective-C, but naturally applies to Phonegap since it can be translated and used via Cordova's Device Motion Plugin . 在Objective-C中提供了相关的代码段,但是自然可以应用于Phonegap,因为它可以通过Cordova的Device Motion插件进行翻译和使用。

Here's the original: 这是原始的:

float x = -[acceleration x];
float y = [acceleration y];
float angle = atan2(y, x);

if(angle >= −2.25 && angle <= −0.75) {
   //OrientationPortrait
} else if(angle >= −0.75 && angle <= 0.75){
   //OrientationLandscapeRight
} else if(angle >= 0.75 && angle <= 2.25) {
   //OrientationPortraitUpsideDown
} else if(angle <= −2.25 || angle >= 2.25) {
   //OrientationLandscapeLeft];
}

Explanation : For any real arguments x and y that are not both equal to zero, atan2(y, x) is the angle in radians between the positive x-axis of a plane and the point given by the specified coordinates on it. 说明 :对于x和y均不等于零的任何实参,atan2(y,x)是平面的正x轴与平面上指定坐标所给定点之间的弧度角。 The angle is positive for counter-clockwise angles, and negative for clockwise angles. 逆时针旋转角度为正,顺时针旋转角度为负。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM