Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

c# - How can I determine if one rectangle is completely contained within another?

I have a theoretical grid of overlapping rectangles that might look something like this:

grid layout

But all I have to work with is a collection of Rectangle objects:

var shapes = new List<Rectangle>();
shapes.Add(new Rectangle(10, 10, 580, 380));
shapes.Add(new Rectangle(15, 20, 555, 100));
shapes.Add(new Rectangle(35, 50, 40, 75));
// ...

What I'd like to do is build a DOM-like structure where each rectangle has a ChildRectangles property, which contains the rectangles that are contained within it on the grid.

The end result should allow me to convert such a structure into XML, something along the lines of:

<grid>
  <shape rectangle="10, 10, 580, 380">
    <shape rectangle="5, 10, 555, 100">
      <shape rectangle="20, 30, 40, 75"/>
    </shape>
  </shape>
  <shape rectangle="etc..."/>
</grid>

But it's mainly that DOM-like structure in memory that I want, the output XML is just an example of how I might use such a structure.

The bit I'm stuck on is how to efficiently determine which rectangles belong in which.

NOTE No rectangles are partially contained within another, they're always completely inside another.

EDIT There will typically be hundreds of rectangles, should I just iterate through every rectangle to see if it's contained by another?

EDIT Someone has suggested Contains (not my finest moment, missing that!), but I'm not sure how best to build the DOM. For example, take the grandchild of the first rectangle, the parent does indeed contain the grandchild, but it shouldn't be a direct child, it should be the child of the parent's first child.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the Contains() of a Rectangle.

Rectangle rect1, rect2;
// initialize them
if(rect1.Continas(rect2))
{
    // do...
}

UPDATE:
For future reference...
It's interesting to add that Rectangle also has IntersectsWith(Rectangle rect) in case you want to check if a rectangle partially collides with another rectangle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...