Skip to content

Instantly share code, notes, and snippets.

@txaiwieser
Created May 11, 2015 19:20
Show Gist options
  • Save txaiwieser/4a12c4b2971393d63b3c to your computer and use it in GitHub Desktop.
Save txaiwieser/4a12c4b2971393d63b3c to your computer and use it in GitHub Desktop.
UIBezierPath+Polygons.swift - UIBezierPath Swift extension for easy creation of polygon paths!
//
// UIBezierPath+Polygons.swift
//
//
// Created by Txai Wieser on 11/05/15.
// Copyright (c) 2015 TDW. All rights reserved.
// Based on: https://github.com/ZevEisenberg/ZEPolygon, thanks man!
import UIKit
extension UIBezierPath {
convenience init(polygonIn rect:CGRect, sides:Int) {
self.init()
if sides < 3 {
assertionFailure("To build a polygon you need 3 ou more sides")
}
let xRadius = CGRectGetWidth(rect)/2
let yRadius = CGRectGetHeight(rect)/2
let centerX = CGRectGetMidX(rect)
let centerY = CGRectGetMidY(rect)
self.moveToPoint(CGPoint(x: centerX + xRadius, y: centerY + 0))
for i in 0..<sides {
let theta = CGFloat(2*M_PI)/CGFloat(sides) * CGFloat(i)
let xCoordinate = centerX + xRadius * cos(theta)
let yCoordinate = centerY + yRadius * sin(theta)
self.addLineToPoint(CGPoint(x: xCoordinate, y: yCoordinate))
}
self.closePath()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment