【发布时间】:2017-10-16 13:54:58
【问题描述】:
我有相交矩形(蓝色)的坐标。 我如何偏移 2 个矩形的起始坐标(左上 X-Y)以防止重叠,前提是我使用了相交矩形的坐标
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 的逻辑,我实现了上面的代码。这在大多数情况下都有效。但在某些图像中,即使检测到相交并添加偏移量,我也会重叠。请参见下面的示例图像。
我要解决的实际问题与这两个问题有关 Translating a Point(X,Y) for Images of Different Sizes from a Custom PictureBox Control
Performing Overlap Detection of 2 Bitmaps
请指教。
更新:
根据您的更新,我已将 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) -
@MBo 谢谢。会检查并回复。
-
@MBo 非常感谢 :) 使用
Math.Abs后,您的第二次更新效果很好。非常感谢您的努力。
标签: c# bitmap geometry gdi+ system.drawing