gpt4 book ai didi

xamarin - 如何以 xamarin 形式获得设备倾斜?

转载 作者:行者123 更新时间:2023-12-02 12:15:25 24 4
gpt4 key购买 nike

我想获得设备的倾斜度,这样我可以用它来测量某些表面的倾斜度,将设备放在表面上。

现在我正在使用此处的 Xamarin 表单设备运动插件 https://github.com/rdelrosario/xamarin-plugins

和下面的代码:

CrossDeviceMotion.Current.Start(MotionSensorType.Accelerometer);

    CrossDeviceMotion.Current.SensorValueChanged += (s, a) =>
{

switch (a.SensorType)
{
case MotionSensorType.Accelerometer:
{
Debug.WriteLine("A: {0},{1},{2}", ((MotionVector)a.Value).X, ((MotionVector)a.Value).Y,
((MotionVector)a.Value).Z);
Exposicao.Inclinacao = ((MotionVector)a.Value).Z;
break;
}
case MotionSensorType.Compass:
{
// Debug.WriteLine("H: {0}", a.Value);
Exposicao.Bussola = (double)a.Value.Value;
break;
}
}
};

指南针部分正常,加速计部分工作正常,但有一些问题。

如果我没记错的话,我得到了 Z 轴的倾斜,所以 z.Value.Value。

这个值对于android和ios是不同的,让我们重点关注android。

当设备平放在平面上时,z 值从 10 开始;如果设备直立,则 z 值从 0 开始,让焦点仅集中在一个象限。

为了实现我所解释的目的,我做错了什么?

如何将这些值转换为 0 到 90 之间的角度?它看起来不是线性的,所以 5 看起来不是 45 度。

谢谢

最佳答案

我可能会针对您正在寻找的功能推出我自己的平台实现。对于您的目的而言,DeviceMotion 库看起来有点简单,从下面的答案可以看出。我很确定您可以将它作为一个很好的起点,但它需要稍微扩展一下。

安卓

在 Android 上,您应该使用 Rotation Vector Sensor它使用卡尔曼滤波器(带有加速度计、磁力计和陀螺仪)来精确测量设备的旋转:

The rotation vector represents the orientation of the device as a combination of an angle and an axis, in which the device has rotated through an angle θ around an axis (x, y, or z). enter image description here

Image from the official Android documentation

iOS:

对于iOS,你必须自己做更多的工作。关键是利用 CMAttitude,它描述了设备相对于初始姿态的姿态。我在这里找到了一个从未知来源保存到我的收藏中的片段(无法注明原作者):

public void CalculateLeanAngle ()
{
motionManager = new CMMotionManager ();
motionManager.DeviceMotionUpdateInterval = 0.02;

if (motionManager.DeviceMotionAvailable) {
motionManager.StartDeviceMotionUpdates(CMAttitudeReferenceFrame.XArbitraryZVertical, NSOperationQueue.CurrentQueue, (data, error) => {
CMQuaternion quat = motionManager.DeviceMotion.Attitude.Quaternion;
double x = quat.x;
double y = quat.y;
double w = quat.w;
double z = quat.z;
double degrees = 0.0;

//Roll
double roll = Math.Atan2 (2 * y * w - 2 * x * z, 1 - 2 * y * y - 2 * z * z);
degrees = Math.Round (-applyKalmanFiltering (roll) * 180.0 / Constants.M_PI);
});
}

public double applyKalmanFiltering (double yaw)
{
if (motionLastYaw == 0)
motionLastYaw = yaw;

float q = 0.1f; // process noise
float r = 0.1f; // sensor noise
float p = 0.1f; // estimated error
float k = 0.5f; // kalman filter gain

double x = motionLastYaw;
p = p + q;
k = p / (p + r);
x = x + k * (yaw - x);
p = (1 - k) * p;
motionLastYaw = x;

return motionLastYaw;
}

enter image description here

Image from the official Xamarin documentation

当我有更多时间时,我会尝试寻找原始来源,但我很确定这可以开箱即用地满足您的目的。

关于xamarin - 如何以 xamarin 形式获得设备倾斜?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45946889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com