JWood - 4 months ago 10
Objective-C Question

# Multiple CGPoints to CGRect

I have a a set of

`CGPoint`
s which represent a shape which is a bit like an upside down 'T' shape, now I want to convert those points into a
`CGRect`
which fits inside the shape, so to create a
`CGRect`
which encompasses the entire shape I just loop through and work out the lowest
`x`
and
`y`
for the top left and the highest
`x`
and
`y`
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
`CGRect`
.

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

Here's what my code above produces:

Here's what I'm trying to achieve:

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

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

Iteratively:

• 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.

Source (Stackoverflow)