0

I have a polygon drawn as an UIBezierPath with 5 coordinates. It is correctly shown and the area is calculated, now I want a button that starts filling the shape until the button is released and calculate the percentage of the filled area. How can I do this efficiently?

enter image description here enter image description here

On the left image there's the current implementation, the right one is what should look like after the logic is implemented.

Thank you in advance!

iDec
  • 707
  • 2
  • 8
  • 16

1 Answers1

0

The polygon being filled has five vertices. Assuming it to be convex, the polygon describing the filled area has either five or six vertices, truncating the original with a horizontal line.

Collect the vertices for these to polygons as two arrays of @[x,y] pairs, and apply this formula to each to compute the areas.

The polygon being filled is constant, so its area need only be computed once. For the filled polygon, as soon as the fill line y is greater than any vertex y, the x*y term for that vertex becomes constant, so you could save a little computational effort there. But, just to get it working, I'd start by recalculating the whole fill area each time the fill line changes. Five or six vertices is peanuts, FPU-wise.

danh
  • 62,181
  • 10
  • 95
  • 136
  • First of all, thanks for answering. I understand what you said and that's the formula I'm applying for the polygon being filled, the fact is, how can I "build" that filled area with animation while a button is pressed?. The idea is to start filling the polygon with an animation and when the button is released get that area filled, but to draw a UIBezierPath you need to know the coordinates previously. – iDec Mar 01 '16 at 16:00
  • Is the question how to perform the animation of the filled polygon, or how to do that while the button is pressed, or how to compute its area? – danh Mar 01 '16 at 16:12
  • The concept for how to animate is `CAKeyframeAnimation`. Keep the coords around for the outer polygon, "intersect" those with a fill line to get the filled coords at several y values of the fill line (each y value where the fill line intersects the outer polygon vertex is the minimal set), those intermediate polygons are your `values` array for the key frame animation. Compute the areas as I describe in the original answer. – danh Mar 01 '16 at 16:17
  • To do this only while a button is being pressed, consider using, instead of a button, a UIView with a UILongPressGestureRecognizer attached. That will provide you with all of the states that a press began and ended. – danh Mar 01 '16 at 16:18
  • Thank you danh, I'll get back to you with the results! – iDec Mar 01 '16 at 16:20