0

Been struggling to come up with a solution to return a rectangle representing the actual intersection between two rectangles.

What I am looking for is much like this: MSDN - Rectangle::Intersect Method (Rectangle, Rectangle)

As the picture shows I would like to have the rectangle colored in green returned from an intersection between two rectangles. Not some boolean value true or false.

Rect intersection data

I will accept a code sample or just plain theory as an answer. Thanks in advance!

4

2 回答 2

6

查看Rectangle.intersection()方法,它是您需要的。

基准intersectionmin/max计算:

    var t:int = getTimer();

    var r3:Rectangle = new Rectangle();
    var r1:Rectangle = new Rectangle(0, 0, 100, 100);
    var r2:Rectangle = new Rectangle(50, 50, 100, 100);
    var i:int;

    for(i = 0; i < 100000; i++)
    {
        r3.left = Math.max(r1.left, r2.left);
        r3.right = Math.min(r1.right, r2.right);
        r3.top = Math.max(r1.top, r2.top);
        r3.bottom = Math.min(r1.bottom, r2.bottom);
    }
    trace("min/max: t = ", (getTimer() - t), "ms");

    t = getTimer();
    for(i = 0; i < 100000; i++)
    {
        r3 = r1.intersection(r2);
    }
    trace("intersection: t = ", (getTimer() - t), "ms");

出去:

min/max: t =  167 ms
intersection: t =  87 ms
于 2013-05-20T13:31:02.493 回答
4
r3.minX = max(r1.minX, r2.minX);
r3.maxX = min(r1.maxX, r2.maxX);
r3.minY = max(r1.minY, r2.minY);
r3.maxY = min(r1.maxY, r2.maxY);

与您对 Rectangle 的实际表示进行转换是读者的练习。

如果r3.minX > r3.maxX || r3.minY > r3.maxY,则不存在交集。否则,如果r3.minX == r3.maxX || r3.minY == r3.maxY,则生成的矩形是退化的。否则,您有一个与正面积的实际交集。

于 2013-05-20T13:34:47.823 回答