Skip to content

Instantly share code, notes, and snippets.

@JaydenIrwin
Forked from jonasreinsch/rounded_polygon_path
Last active March 8, 2018 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JaydenIrwin/ee4f7e4518ecf1ec8a32e2aaeab6ace3 to your computer and use it in GitHub Desktop.
Save JaydenIrwin/ee4f7e4518ecf1ec8a32e2aaeab6ace3 to your computer and use it in GitHub Desktop.
function to create a UIBezierPath for a (rounded corner) polygon in Swift
// this is a port from the following Objective C code
// http://stackoverflow.com/a/24770675/1269132
func roundedPolygonPath(squareLength: CGFloat, lineWidth: CGFloat, sides: Int, cornerRadius: CGFloat) -> UIBezierPath {
let path = UIBezierPath()
// how much to turn at every corner
let theta = 2.0 * CGFloat.pi / CGFloat(sides)
// offset from which to start rounding corners
let offset = cornerRadius * tan(theta / 2.0)
let sideLength: CGFloat = {
// calculate the length of the sides of the polygon
var length = squareLength - lineWidth
// if not dealing with polygon which will be square with all sides...
if sides % 4 != 0 {
// offset it inside a circle inside the square
length = length * cos(theta / 2.0) + offset/2.0
}
return length * tan(theta / 2.0)
}()
// start drawing at `point` in lower right corner
var point = CGPoint(x: squareLength / 2.0 + sideLength / 2.0 - offset, y: squareLength - (squareLength - length) / 2.0)
var angle = CGFloat.pi
path.move(to: point)
// draw the sides and rounded corners of the polygon
for _ in 0..<sides {
point = CGPoint(x: point.x + (sideLength - offset * 2.0) * cos(angle), y: point.y + (sideLength - offset * 2.0) * sin(angle))
path.addLine(to: point)
let center = CGPoint(x: point.x + cornerRadius * cos(angle + .pi/2), y: point.y + cornerRadius * sin(angle + .pi/2))
path.addArc(withCenter: center, radius: cornerRadius, startAngle: angle - .pi/2, endAngle: angle + theta - .pi/2, clockwise: true)
point = path.currentPoint // we don't have to calculate where the arc ended ... UIBezierPath did that for us
angle += theta
}
path.close()
return path
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment