开发者

Algorithm for finding a rectangle constrained to its parent

Basically what I want to do is illustrated here:

Algorithm for finding a rectangle constrained to its parent

I start with A and B, then B is conformed to A to create C.

The idea is, given TLBR rectangles A, B, make C

I also need to know if it produces an emp开发者_运维知识库ty rectangle (B outside of A case).

I tried this but it just isn't doing what I want:

if(clipRect.getLeft() > rect.getLeft())
    L = clipRect.getLeft();
else
    L = rect.getLeft();

if(clipRect.getRight() < rect.getRight())
    R = clipRect.getRight();
else
    R = rect.getRight();

if(clipRect.getBottom() > rect.getBottom())
    B = clipRect.getBottom();
else
    B = rect.getBottom();

if(clipRect.getTop() < rect.getTop())
    T = clipRect.getTop();
else
    T = rect.getTop();

if(L < R && B < T)
{
    clipRect = AguiRectangle(0,0,0,0);
}
else
{
    clipRect = AguiRectangle::fromTLBR(T,L,B,R);
}

Thanks


You seem to have a mistake in the final condition checking whether or not the intersection rectangle is empty.

You check L < R && B < T, but it seems like the condition for an empty rectangle should be:

L > R || B < T.

By the way, you can make your code a little simpler and easier to read by using Min and Max functions. You have a lot of this pattern:

if (x < y)
    a = x;
else
    a = y;

Which can be written simply as

a = Min(x, y);

Edit

Another mistake is that you take the maximum bottom and the minimum top. You should be taking the minimum bottom and the maximum top. (Assuming the rectangles correspond to screen coordinates, where the top actuallly has lower y values.


Logically, these are two different problems. I would first write an is_intersected() function returning an appropriate boolean value.

If the rects do intersect, I would then perform a clip operation that resembled the following pseudocode:

C.left.x = max(A.left.x, B.left.x);
C.right.x = min(A.right.x, B.right.x);

C.left.y = max(A.left.y, B.left.y);
C.right.y = min(A.right.y, B.right.y);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜