ano*_*ous 15 geometry core-graphics objective-c cgrect
我怎么CGRect能从另一个减去?我希望结果R1 - R2是R1的最大子矩形,不与R2相交.
例1:
+----------------------------------+ | +--------+ | | | R2 | | | | | | | +--------+ R1 | | | | | | | +----------------------------------+
R3 = CGRectSubstract(R2,R1);
+----------------------+
| |
| |
| |
| R3 |
| |
| |
| |
+----------------------+
例2:
+-----------------------+----------+ | | | | | R2 | | | | | R1 +----------+ | | | | | | +----------------------------------+
R3 = CGRectSubstract(R2,R1);
+-----------------------+ | | | | | | | R3 | | | | | | | +-----------------------+
例3:
+----------------------------------+ | | | | | | | R1 | | +---------+ | | | | | | | R2 | | +---------+---------+--------------+
R3 = CGRectSubstract(R2,R1);
+----------------------------------+ | | | | | R3 | | | +----------------------------------+
cob*_*bal 20
你的定义是相当模糊的,是什么说减法是水平的还是垂直的?我建议使用CGRectIntersection和CGRectDivide的组合,并指定消除歧义的方向.
(未测试,甚至编译)
CGRect rectSubtract(CGRect r1, CGRect r2, CGRectEdge edge) {
// Find how much r1 overlaps r2
CGRect intersection = CGRectIntersection(r1, r2);
// If they don't intersect, just return r1. No subtraction to be done
if (CGRectIsNull(intersection)) {
return r1;
}
// Figure out how much we chop off r1
float chopAmount = (edge == CGRectMinXEdge || edge == CGRectMaxXEdge)
? intersection.size.width
: intersection.size.height;
CGRect r3, throwaway;
// Chop
CGRectDivide(r1, &throwaway, &r3, chopAmount, edge);
return r3;
}
Run Code Online (Sandbox Code Playgroud)