Search code examples
iosobjective-cgeometrypolygonarea

Wrong area calculation objective-c?


I have an array with 5 CGPoints (v0, v1, v2, v3, v4) which are the vertex of the shape implemented like this:

_arrayVertex = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithCGPoint:v0], [NSValue valueWithCGPoint:v1], [NSValue valueWithCGPoint:v2], [NSValue valueWithCGPoint:v3], [NSValue valueWithCGPoint:v4], nil];

Then, I calculate the area with those points:

- (float)calculateArea {

    float area = 0;
    int N = (int)_arrayVertex.count;

    for (int i = 0; i < N-1; i++) {

        float term = ([_arrayVertex[i] CGPointValue].x * [_arrayVertex[i+1 % N] CGPointValue].y -
                  [_arrayVertex[i+1 % N] CGPointValue].x * [_arrayVertex[i] CGPointValue].y)/2.0;

        area += term;
    }

    return fabsf(area);

}

Is the area correctly calculated? Am I missing something?. Thank you in advance.


Solution

  • sbim:

    - (float)calculateArea {
    
        float area = 0;
        int N = (int)_arrayVertex.count;
    
        for (int i = 0; i < N; i++) {
    
            float term = ([_arrayVertex[i] CGPointValue].x * [_arrayVertex[(i+1) % N] CGPointValue].y -
                  [_arrayVertex[(i+1) % N] CGPointValue].x * [_arrayVertex[i] CGPointValue].y)/2.0;
    
            area += term;
        }
    
        return fabsf(area);
    
    }