JWood JWood - 1 year ago 55
Objective-C Question

Multiple CGPoints to CGRect

I have a a set of

s which represent a shape which is a bit like an upside down 'T' shape, now I want to convert those points into a
which fits inside the shape, so to create a
which encompasses the entire shape I just loop through and work out the lowest
for the top left and the highest
for the bottom right which is great but leaves white areas outside of the image, how could I figure out the largest rectangle without white areas so the final shape is more like an '|' shape? My code so far:

CGPoint topLeft = CGPointZero;
CGPoint bottomRight = CGPointZero;
for( NSValue *value in points ) {
CGPoint point = [value CGPointValue];
if( topLeft.x == 0 || topLeft.x > point.x ) shapeRect.x = point.x;
if( topLeft.y == 0 || topLeft.y > point.y ) shapeRect.y = point.y;
if( bottomRight.x < point.x ) bottomRight.x = point.x;
if( bottomRight.y < point.y ) bottomRight.y = point.y;
CGRect shapeRect = CGRectMake(topLeft.x, topLeft.y, bottomRight.x - topLeft.x, bottomRight.y - topLeft.y);

EDIT: I've drawn some pics to show what I'm trying to achieve. Grey areas show the

Here's the image shape, I have coordinates for each point in the shape:

Image Hosted by ImageShack.us

Here's what my code above produces:

Image Hosted by ImageShack.us

Here's what I'm trying to achieve:

Image Hosted by ImageShack.us


If I did not misunderstand the question, your aim is to find the blue points:
enter image description here

If I'm correct, then it's enough for you to store two points (say topL and topR) and a value (say bottom).

enter image description here


  • check if the current point has y < topL.y and eventually update topL and topR.
    • If instead y == topL.y check if current x is less than topL.x. If yes update topL
    • otherwise check if current x>topR.x; if yes update topR.
  • check if current y>bottom. If yes update bottom.

Note that when I say "update topL" I mean both x and y.

At the end you can get your bottom-left and bottom-right points using x coordinate of topL and topR and setting y coordinate to bottom.