Search code examples
iosshapesarea

How to calculate area of an organic shape?


I want to know its possible to calculate the area of an organic shape. The shape im trying to calculate looks something like this:

Imagine its drawn by CGPoints

Is there a special function for this? Im thinking maybe CoreImage or Quartz or maybe opengl.


Solution

  • If the boundary path consists only of straight line segments and does not intersect itself then you can use the following formula to compute the area of the enclosed region (from https://en.wikipedia.org/wiki/Polygon#Area_and_centroid):

    CGPoint points[N]; 
    
    CGFloat area = 0;
    for (int i = 0; i < N; i++) {
        area += (points[i].x * points[(i+1) % N].y - points[(i+1) % N].x * points[i].y)/2.0;
    }
    

    where points[0], ... , points[N-1] are the starting points of the line segments in counter-clockwise order.

    For more complicate path segments such as Bézier curves, you can subdivide each segment into small parts that can be approximated by line segments.