我试图在Accelerometer.Shaken事件中实现某种处理程序,然后我发现Windows 10上不支持此事件,可以从answer here看到。
现在,即使动摇事件不起作用,Accelerometer.ReadingChanged
事件也能正常工作。
所以我在想,是否有可能从该数据手动检测摇动手势?我的意思是,这可能是可能的,但我真的不知道从哪里开始,有没有人有想法?
每隔x毫秒就会得到X,Y和Z坐标,必须有一些方法可以根据该数据计算摇动手势。
感谢您的帮助!
答案 0 :(得分:3)
没关系,我最后写了自己的课程来解决这个问题,我会把它留在这里,以防它对其他人有用:
/// <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;