2

I can combine rect1 with rect2 using CGRectUnion() and get a combined rect3 fine.

Is it possible to subtract a rect1 from a rect3 (which contains rect1) and get a remaining part of rect?

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
eugene
  • 39,839
  • 68
  • 255
  • 489
  • 3
    `CGRectUnion()` doesn't really do a true union of rectangles, it just returns the smallest rectangle that completely contains both of the source rectangles. What kind of result type are you expecting? I doubt that a subtraction would provide a rectangle in most cases. – Brad Larson Jan 25 '11 at 21:55
  • Closely related: [Subtract CGRect from CGRect -- largest piece of one not containing the other](http://stackoverflow.com/q/4811623). Based on the diagrams there, the chosen definition is that the result is a subrectangle of the first which doesn't intersect the second. This isn't exactly subtraction, of course, but it may be useful. – jscs Jul 06 '13 at 21:58

3 Answers3

3

As Brad Larson said, you can't do this in Quartz, because the CGRect functions work with nothing but rects and their component parts (points, sizes, and single numbers).

If you were programming the Mac, I would suggest using another API named HIShape. It's the modern successor to QuickDraw Regions, and as such, it is capable of non-rectangular shapes. Unfortunately, though HIShape is still available on 64-bit Mac OS X, it is not available on iOS.

If you really need something like this, you will have to write it yourself, including your own HIShape-like not-necessarily-rectangular shape class.

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
1

Try CGRectIntersection if I could understand you correctly.

Max
  • 16,679
  • 4
  • 44
  • 57
  • `CGRectIntersection` returns the intersection of two rects. What he asked for is if there is a method to subtract one rect from another. `originalRect - CGRectIntersection(originalRect, otherRect)` – pronebird Nov 14 '15 at 14:11
0

well, it depends... on how rect3 contains rect1... i mean, it may happens that the resulting area is no more a rect... for example, if rect1 is all inside rect3 the remaining area is not a rect, so you couldn't use the CGRect object. You could obtain a rect just in case rect3 and rect1 share completely a side and have it (all of it) in common. So i need to know what kind of objet you wanna obtain by that subtraction... may it be a new image with 2 different areas coloured? or slit the resuting area in more CGrect (upper rect, left, bitton, right...) what are you going to do with the resulting "object"?

luca

meronix
  • 6,175
  • 1
  • 23
  • 36