gpt4 book ai didi

c# - UWP 上的 Accelerometer.Shaken 事件不起作用,有什么解决方案吗?

转载 作者:行者123 更新时间:2023-11-30 21:51:59 29 4
gpt4 key购买 nike

我试图对 Accelerometer.Shaken 事件实现某种处理程序,然后我发现 Windows 10 尚不支持此事件,从 answer here 可以看出。

现在,即使 shaken 事件不起作用,Accelerometer.ReadingChanged 事件也能正常工作。所以我在想,是否可以从该数据中手动检测摇晃手势?我的意思是,这可能是可能的,但我真的不知道从哪里开始,有人知道吗?

您每 x 毫秒获得一次 X、Y 和 Z 坐标,一定有某种方法可以根据该数据计算摇动手势。

感谢您的帮助!

最佳答案

没关系,我最终编写了自己的类来解决问题,我会把它留在这里以防它对其他人有用:

/// <summary>
/// A static class that manages the Shaken event for the Accelerometer class
/// </summary>
public static class CustomAccelerometer
{
// The minimum acceleration value to trigger the Shaken event
private const double AccelerationThreshold = 2;

// The minimum interval in milliseconds between two consecutive calls for the Shaken event
private const int ShakenInterval = 500;

private static bool _AccelerometerLoaded;

private static Accelerometer _DefaultAccelerometer;

/// <summary>
/// Gets the current Accelerometer in use
/// </summary>
private static Accelerometer DefaultAccelerometer
{
get
{
if (!_AccelerometerLoaded)
{
_AccelerometerLoaded = true;
_DefaultAccelerometer = Accelerometer.GetDefault();
}
return _DefaultAccelerometer;
}
}

private static DateTime _ShakenTimespan = DateTime.Now;

private static bool _Enabled;

/// <summary>
/// Gets or sets whether or not the Accelerometer is currently enabled and can raise the Shaken event
/// </summary>
public static bool Enabled
{
get { return _Enabled; }
set
{
if (_Enabled != value && DefaultAccelerometer != null)
{
if (value) DefaultAccelerometer.ReadingChanged += _DefaultAccelerometer_ReadingChanged;
else DefaultAccelerometer.ReadingChanged -= _DefaultAccelerometer_ReadingChanged;
}
_Enabled = value;
}
}

// Handles the ReadingChanged event and raises the Shaken event when necessary
private static void _DefaultAccelerometer_ReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgs args)
{
double g = Math.Round(args.Reading.AccelerationX.Square() + args.Reading.AccelerationY.Square() + args.Reading.AccelerationZ.Square());
if (g > AccelerationThreshold && DateTime.Now.Subtract(_ShakenTimespan).Milliseconds > ShakenInterval)
{
_ShakenTimespan = DateTime.Now;
Shaken?.Invoke(null, EventArgs.Empty);
}
}

/// <summary>
/// Raised whenever the Accelerometer detects a shaking gesture
/// </summary>
public static event EventHandler Shaken;
}

要使用它,只需启用它并订阅它的事件:

CustomAccelerometer.Enabled = true;
CustomAccelerometer.Shaken += (s, e) =>
{
Debug.WriteLine("The device was shaken!");
};

编辑:忘记添加Square方法代码,这里是:

/// <summary>
/// Returns the square of the given double value
/// </summary>
/// <param name="value">The input value</param>
public static double Square(this double value) => value * value;

关于c# - UWP 上的 Accelerometer.Shaken 事件不起作用,有什么解决方案吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35075193/

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