将问题分解到每个轴的基础上。您的矩形可以根据它们在每个轴上的跨度来定义 - 在每个轴上找到矩形开始或结束的有趣点,然后用这些术语定义您的结果。这将为您提供 6 个不同区域的矩形,您可以轻松地将它们组合成您所示的四个,或者如果需要,可以消除退化的零面积矩形。
这是一个Java实现:
public class Rect
{
private float minX, maxX, minY, maxY;
public Rect( float minX, float maxX, float minY, float maxY )
{
this.minX = minX;
this.maxX = maxX;
this.minY = minY;
this.maxY = maxY;
}
/**
* Finds the difference between two intersecting rectangles
*
* @param r
* @param s
* @return An array of rectangle areas that are covered by either r or s, but
* not both
*/
public static Rect[] diff( Rect r, Rect s )
{
float a = Math.min( r.minX, s.minX );
float b = Math.max( r.minX, s.minX );
float c = Math.min( r.maxX, s.maxX );
float d = Math.max( r.maxX, s.maxX );
float e = Math.min( r.minY, s.minY );
float f = Math.max( r.minY, s.minY );
float g = Math.min( r.maxY, s.maxY );
float h = Math.max( r.maxY, s.maxY );
// X = intersection, 0-7 = possible difference areas
// h +-+-+-+
// . |5|6|7|
// g +-+-+-+
// . |3|X|4|
// f +-+-+-+
// . |0|1|2|
// e +-+-+-+
// . a b c d
Rect[] result = new Rect[ 6 ];
// we'll always have rectangles 1, 3, 4 and 6
result[ 0 ] = new Rect( b, c, e, f );
result[ 1 ] = new Rect( a, b, f, g );
result[ 2 ] = new Rect( c, d, f, g );
result[ 3 ] = new Rect( b, c, g, h );
// decide which corners
if( r.minX == a && r.minY == e || s.minX == a && s.minY == e )
{ // corners 0 and 7
result[ 4 ] = new Rect( a, b, e, f );
result[ 5 ] = new Rect( c, d, g, h );
}
else
{ // corners 2 and 5
result[ 4 ] = new Rect( c, d, e, f );
result[ 5 ] = new Rect( a, b, g, h );
}
return result;
}
}