3

I have tried to follow this answer

It works fine for creating the polygons, however I can see that it doesn't reach the edges of the containing rectangle.

The following gif shows what I mean. Especially for the 5 sided polygon it is clear that it doesn't "span" the rectangle which I would like it to do

A sample gif to show that the polygon sometimes doesn't reach all the edges

This is the code I use for creating the vertices

  func verticesForEdges(_edges: Int) -> [CGPoint] {
    let offset = 1.0
    var vertices: [CGPoint] = []

    for i in 0..._edges {
      let angle = M_PI + 2.0 * M_PI * Double(i) / Double(edges)
      var x = (frame.width / 2.0) * CGFloat(sin(angle)) + (bounds.width / 2.0)
      var y = (frame.height / 2.0) * CGFloat(cos(angle)) + (bounds.height / 2.0)
      vertices.append(CGPoint(x: x, y: y))
    }

    return vertices
  }

And this is the code that uses the the vertices

override func layoutSublayers() {
    super.layoutSublayers()

    var polygonPath = UIBezierPath()
    let vertices = verticesForEdges(edges)

    polygonPath.moveToPoint(vertices[0])

    for v in vertices {
      polygonPath.addLineToPoint(v)
    }

    polygonPath.closePath()
    self.path = polygonPath.CGPath

  }

So the question is. How do I make the the polygons fill out the rectangle

Update:

The rectangle is not necessarily a square. It can have a different height from its width. From the comments it seems that I am fitting the polygon in a circle, but what is intentioned is to fit it in a rectangle.

Community
  • 1
  • 1
chrs
  • 5,906
  • 10
  • 43
  • 74
  • 1
    You need to define your task more clear. Do you restrict polygons to regular ones? What is a bounding rectangle? What are restrictions on the bounding rectangle? Consider two polygons: a regular triangle and a square. Are their bounding rectangles different? – dmitri Jan 28 '15 at 03:22
  • Your code is fitting the polygon in a circle, not in the square. – rmaddy Jan 28 '15 at 03:55
  • you can scale the points to fit one axis by multipliyng all points by needed_size/actual_size but if you want to fit both axises then you have to have rectangle aspect ratio in the correct manner or try more rotated position and fit the one that is closest to your aspect. but there is not guaranteed a solution for any N nor aspect ratio ... – Spektre Jan 28 '15 at 08:17

1 Answers1

1

If the first (i=0) vertice is fixed at the middle of top rectangle edge, we can calculate minimal width and height of bounding rectangle:
The rightmost vertice index

ir = (N + 2) / 4   // N/4, rounded to the closest integer, not applicable to triangle
MinWidth = 2 * R * Sin(ir * 2 * Pi / N)

The bottom vertice index

ib = (N + 1) / 2   // N/2, rounded to the closest integer
MinHeight = R * (1 +  Abs(Cos(ib * 2 * Pi / N)))

So for given rectangle dimensions we can calculate R parameter to inscribe polygon properly

MBo
  • 77,366
  • 5
  • 53
  • 86