这是在 Win32 中左键单击并在 FMX 表单上移动 TRectangle 所需的完整代码(尚未在移动设备上尝试过)。只需创建一个新的 FireMonkey 多设备应用程序并在其上放置一个 TRectangle 和一个 TButton。
要添加到表单的类声明的代码(在 .h 文件中,就在 class TForm1 : public TForm { 下):
bool fMouseIsDown; // gets set to TRUE when left mouse click on the rectangle
TPointF fMousePosGlobal; // this is the mouses position relative to the screen
TPointF fMousePosForm; // this is the mouse pos relative to the form
TPointF captionOffset; // this is a small offset necessary since the form's TOP and LEFT are outside of form's client area due to caption bar and left edge of form
TPointF fMouseInRectAtClick; // this is the mouse pos relative to the rectangle (top left of rectangle is 0,0)
要添加到矩形的Rectangle1MouseDown 事件的代码:
if (Button == 0) { // 0 for left mb, 1 for right mb
fMouseIsDown = true;
fMouseInRectAtClick.X = X; //mouse pos with respect to rectangle at time of click
fMouseInRectAtClick.Y = Y;
}
添加到矩形的Rectangle1MouseMove 事件的代码(也添加到表单的FormMouseMove 或者有时您会在快速拖动时丢失矩形):
fMousePosGlobal = Screen->MousePos(); //mouse global pos
fMousePosForm.X = fMousePosGlobal.X - Form1->Left; // mouse pos relative to the form
fMousePosForm.Y = fMousePosGlobal.Y - Form1->Top;
if (fMouseIsDown) {
Form1->Rectangle1->Position->X = fMousePosForm.X - captionOffset.X - fMouseInRectAtClick.X;
Form1->Rectangle1->Position->Y = fMousePosForm.Y - captionOffset.Y - fMouseInRectAtClick.Y;
}
要添加到Rectangle1MouseUp 事件的代码:
fMouseIsDown = false; // add this to the form's MouseUp too in case you "lose" the rectangle on a drag. That only happened when i forget to set the offsets.
要添加到 Button 的 Button1Click 事件的代码:
captionOffset.X = 8.0; // this accounts for the width of the form left edge
captionOffset.Y = 30.0; // this accounts for the height of the form caption
// if you don't add this your "drag point" on the rectangle will jump as soon as you start the drag.
感谢汉斯的指导!
另外,我注意到在其他控件上移动时拖动并不顺畅。如果这让您感到困扰,那么您需要将那些其他控件“HitTest”设置为 false,以便他们忽略它。如果您想在移动鼠标和矩形时查看所有 TPointF 坐标,请添加 TEdit 框 - 在尝试计算坐标时会有所帮助。