我有以下情况,其中矩形重叠。
我有交集矩形(蓝色)的坐标。
如果我有交集矩形的坐标,如何偏移两个矩形的起始坐标(左上角X-Y),以防止重叠。
使用这段代码时,第二个图像在某些情况下会移动得太远。请告诉我这段代码是否正确。
![enter image description here](https://istack.dev59.com/9nC25.webp)
rectangle3 = Rectangle.Intersect(rectangle1, rectangle2);
更新:
根据 @MBo 的更新,我已经添加了以下代码。
Blue = Rectangle.Intersect(First, Second);
if (Blue != Rectangle.Empty)
{
if (First.Right == Blue.Right)
{
imgpoint.X += (Blue.Right - Blue.Left);
}
if (First.Bottom == Blue.Bottom)
{
imgpoint.Y += (Blue.Bottom - Blue.Top);
}
if (First.Left == Blue.Left)
{
imgpoint.X-= (Blue.Right - Blue.Left);
}
if (First.Top == Blue.Top)
{
imgpoint.Y -= (Blue.Bottom - Blue.Top);
}
}
更新2:
根据@MBo的逻辑,我实现了上面的代码。在大多数情况下,这个方法是有效的。但是,在某些图像中,即使检测到交叉并添加了偏移量,仍会出现重叠。请参见下面的示例图像。
我正在尝试解决的实际问题与以下两个问题相关: 从自定义PictureBox控件缩放不同大小的图像的点(X,Y)的转换
请给予建议。
更新:
根据您的更新,我已将Delphi代码翻译成了C#。
Blue = Rectangle.Intersect(First, Second);
if (Blue != Rectangle.Empty)
{
int dcy,dcx;
int dy,dx;
int fl=First.Left,fw=First.Width,fh=First.Height,ft=First.Top,fb=First.Bottom,fr=First.Right;
int sl=Second.Left,sr=Second.Right,st=Second.Top,sb=Second.Bottom,sw=Second.Width,sh=Second.Height;
dcy = (sb + st) - (fb + ft); //doubled center y-difference
dcx = (sl + sr) - (fl + fr);
if ((int)(dcx) >= (fw + sw) || ((int)(dcy) >= (fh + sh)))
{//no intersection
}
else
{
dx = fw + sw - (int)dcx; //doubled needed x-shift absolute value
dy = fh + sh - (int)dcy;
if (dx > dy)
{
if (dcy < 0)
{
dy = - dy/2;
}
else
{
dy = dy/ 2; //needed y-shift accounting for direction
}
dx = 0;
}
else
{
if (dcy < 0)
{
dx = - dx/ 2;
}
else
{
dx = dx/2;
dy = 0;
}
}
imgpoint.X+=dx;
imgpoint.Y+=dy;
}
}
使用这段代码时,第二个图像在某些情况下会移动得太远。请告诉我这段代码是否正确。
(int)(dcx)
和dcy
,需要使用绝对值(类似于math.abs
)的地方。 - MBoMath.Abs
后,你的第二次更新非常好用。真的非常感谢你的努力。 - techno