【发布时间】:2010-07-03 22:09:46
【问题描述】:
假设我有以下重叠的矩形(“a”和“b”):
aaaaaaaa
aaaaccccbbbbb
aaaaccccbbbbb
aaaaccccbbbbb
bbbbbbbbb
bbbbbbbbb
我已经看到很多关于如何计算内部矩形 ("c") 的 面积 的想法,但我将如何获取实际的上/左/下/右坐标为了它?
【问题讨论】:
标签: c#
假设我有以下重叠的矩形(“a”和“b”):
aaaaaaaa
aaaaccccbbbbb
aaaaccccbbbbb
aaaaccccbbbbb
bbbbbbbbb
bbbbbbbbb
我已经看到很多关于如何计算内部矩形 ("c") 的 面积 的想法,但我将如何获取实际的上/左/下/右坐标为了它?
【问题讨论】:
标签: c#
【讨论】:
两个矩形重叠区域的X坐标可以按照如下逻辑求出。
要找到 Y 坐标,请在四个假设中的最后一个以及所有三种情况下用 Y 代替 X。
假设:
A 和 B 是矩形(其边沿 X 轴和 Y 轴对齐),
每个矩形由两个点定义 (xmin / ymin) – (xmax / ymax)
其中 xmin xmax 和 ymin ymax .
A.xmin B.xmin
案例 1 - 无重叠:
+--------+
|A |
| | +----+
| | |B |
| | +----+
| |
+--------+
A.xmin A.xmaxB.xminB.xmax ⇒ 没有重叠。
案例 2 - 一些重叠:
+--------+
|A |
| +--+-+
| |B | |
| +--+-+
| |
+--------+
A.xmin B.xminA.xmaxB.xmax ⇒ 重叠 X 坐标:B.xmin – A.xmax
案例 3 — 完全重叠:
+--------+
|A |
| +----+ |
| |B | |
| +----+ |
| |
+--------+
A.xmin B.xminB.xmaxA.xmax ⇒ 重叠 X 坐标:B.xmin – B.xmax
P.S.:您实际上可以进一步简化此算法。重叠 X 坐标始终为:
max(A.xmin, B.xmin) – min(A.xmax , B.xmax)
除非第二个值小于第一个值;这意味着没有重叠。
【讨论】:
static internal Rectangle intersect(Rectangle lhs, Rectangle rhs)
{
Dimension lhsLeft = lhs.Location.X;
Dimension rhsLeft = rhs.Location.X;
Dimension lhsTop = lhs.Location.Y;
Dimension rhsTop = rhs.Location.Y;
Dimension lhsRight = lhs.Right;
Dimension rhsRight = rhs.Right;
Dimension lhsBottom = lhs.Bottom;
Dimension rhsBottom = rhs.Bottom;
Dimension left = Dimension.max(lhsLeft, rhsLeft);
Dimension top = Dimension.max(lhsTop, rhsTop);
Dimension right = Dimension.min(lhsRight, rhsRight);
Dimension bottom = Dimension.min(lhsBottom, rhsBottom);
Point location = new Point(left, top);
Dimension width = (right > left) ? (right - left) : new Dimension(0);
Dimension height = (bottom > top) ? (bottom - top) : new Dimension(0);
return new Rectangle(location, new Size(width, height));
}
【讨论】:
假设:
Points of rectangle R1: R1.A(x,y), R1.B(x,y), R1.C(x,y), R1.D(x,y)
Points of rectangle R2: R2.A(x,y), R2.B(x,y), R2.C(x,y), R2.D(x,y)
Overlapping rectangle RO: RO.A(x,y), RO.B(x,y), RO.C(x,y), RO.D(x,y)
Standard cartesian coordinates (positive is right and upwards).
重叠矩形 RO 用 C# 计算如下:
RO.A.x = Math.Min(R1.A.x, R2.A.x);
RO.A.y = Math.Max(R1.A.y, R2.A.y);
RO.C.x = Math.Max(R1.C.x, R2.C.x);
RO.C.y = Math.Min(R1.C.y, R2.C.y);
RO.B(x,y) and RO.D(x,y) = ....
内矩形RI:
将上述解决方案中的最小值和最大值交换为重叠矩形 RO。
【讨论】:
我为我的项目使用了一个抽象验证器,并检查是否某些布局控件重叠我从布局图形中创建了矩形:
RuleFor(p => DoControlsIntersect(p.PageControls.Select(x => new Rectangle(x.Row, x.Column, x.Width, x.Height)).ToList())).Equal(false).WithMessage(OverlappingFields);
private bool DoControlsIntersect(List<Rectangle> rectangles)
{
return rectangles.Any(rect => rectangles.Where(r => !r.Equals(rect)).Any(r => r.IntersectsWith(rect)));
}
【讨论】: