JWood - 10 months ago 37

Objective-C Question

I have a a set of

`CGPoint`

`CGRect`

`CGRect`

`x`

`y`

`x`

`y`

`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:

Answer

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`

.

- If instead
- 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.