我有一个事件函数,当释放鼠标时调用,当两个形状叠加时,它们应该被“合并”,并且应该在这个地方创建另一个形状。
void __fastcall TForm1::ShapeMouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y)
{
TShape* shape = dynamic_cast<TShape*>(Sender);
if (shape) {
shape->Tag = 0;
if (!Panel1->BoundsRect.Contains(shape->BoundsRect)) {
shape->Left = TagFloat;
shape->Top = TagFloat2;
}
else {
// Проверяем наложение на другие квадраты
for (int i = 0; i < Panel1->ControlCount; ++i) {
TShape* otherShape = dynamic_cast<TShape*>(Panel1->Controls[i]);
if (otherShape && otherShape != shape) {
if (shape->BoundsRect.IntersectsWith(otherShape->BoundsRect)) {
//Application->MessageBox(L"Условие выполнилось", L"Тест");
int left = std::max(shape->Left, otherShape->Left);
int top = std::max(shape->Top, otherShape->Top);
int right = std::min(shape->Left + shape->Width, otherShape->Left + otherShape->Width);
int bottom = std::min(shape->Top + shape->Height, otherShape->Top + otherShape->Height);
int intersectionWidth = right - left;
int intersectionHeight = bottom - top;
if (intersectionWidth > 0 && intersectionHeight > 0 && intersectionWidth * intersectionHeight > 0.5 * shape->Width * shape->Height) {
TShape* newShape = new TShape(Panel1);
newShape->Parent = Panel1;
newShape->Width = shape->Width;
newShape->Height = shape->Height;
newShape->Left = shape->Left;
newShape->Top = shape->Top;
newShape->Shape = stEllipse;
newShape->Brush->Color = clRed;
newShape->OnMouseDown = ShapeMouseDown;
newShape->OnMouseMove = ShapeMouseMove;
newShape->OnMouseUp = ShapeMouseUp;
Panel1->RemoveControl(shape);
Panel1->RemoveControl(otherShape);
delete shape;
delete otherShape;
break;
}
}
}
}
}
}
}
但问题恰恰是条件不满足
我查看代码并注意到条件 if(!Panel1->BoundsRect.Contains(shape->BoundsRect)) 始终被填充,这对于对象返回其位置来说是合乎逻辑的。很可能我错误地设置了交叉点检查。我们需要删除检查
if (!Panel1->BoundsRect.Contains(shape->BoundsRect))
检查else
::if(otherShape && otherShape != shape && shape->BoundsRect.IntersectsWith(otherShape->BoundsRect)