本文整理自网络,侵删。
当您想在摇动智能手机时执行某些操作时,没有像OnShake这样方便的事件。不幸的是,仅凭传感器无法确定它是被摇动还是被移动。如果您搜索诸如“ Android抖动检测”之类的关键字,那么每个人都会以各种逻辑对其进行检测。(基本上是使用加速度传感器检测到的)
我用Delphi开发的应用程序实现了它。加速度传感器组件TMotionSensor和TTimer用于通过粗略算法检测挥杆宽度和速度。
粗略算法如果在一定时间段(0.3秒)内摆动宽度为±1或更大,则将其计数,如果计数为3或更大,则将其视为抖动。由于存在X,Y和Z方向的晃动,因此将(X + Y + Z在基点处)-(X + Y + Z在时间终点处)的值用作摆动宽度。
设计画面不要忘记将MotionSensor Active设置为True
unit Unit1;
interface
uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, System.Sensors, System.Sensors.Components;
type TForm1 = class(TForm) ToolBar1: TToolBar; Switch1: TSwitch; Label1: TLabel; Timer1: TTimer; MotionSensor1: TMotionSensor; procedure Timer1Timer(Sender: TObject); procedure Switch1Switch(Sender: TObject); procedure FormCreate(Sender: TObject); private { private 宣言 } public keepPoint: Double; //保存位置 shakeCount: Integer; //摆动计数 { public 宣言 } end;
var Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.FormCreate(Sender: TObject);begin// 初期化 keepPoint := 0; shakeCount := 0; Label1.Text := ' ';end;
procedure TForm1.Switch1Switch(Sender: TObject);begin//初始化计数的当开关被导通并基本粗糙的保存位置
if Switch1.IsChecked then begin shakeCount := 0; Label1.Text := ' '; keepPoint := MotionSensor1.Sensor.AccelerationX + MotionSensor1.Sensor.AccelerationY + MotionSensor1.Sensor.AccelerationZ; end;
//定时器控制激活
Timer1.Enabled := Switch1.IsChecked;end;
procedure TForm1.Timer1Timer(Sender: TObject);var mPoint: Double; begin//如果摆动次数为3个或更多,它被视为一摇
if shakeCount > 3 then begin Label1.Text := '摇'; shakeCount := 0; Switch1.IsChecked := False; exit; end;
//当前位置
mPoint := MotionSensor1.Sensor.AccelerationX + MotionSensor1.Sensor.AccelerationY + MotionSensor1.Sensor.AccelerationZ;
if ((keepPoint - mPoint) > 1) or ((keepPoint - mPoint) < -1) then begin // 振 shakeCount := shakeCount + 1; end;
//当前粗略位置
keepPoint := mPoint;
end;
end.
相关阅读 >>
更多相关阅读请进入《Delphi》频道 >>