Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Darwin
- private typealias Point = (x: CGFloat, y: CGFloat)
- extension UIBezierPath {
- public convenience init(rect: CGRect, cornerRadius radius: CGFloat, roundedCorners: UIRectCorner = .AllCorners) {
- self.init()
- let path = Path(size: rect.size, radius: radius, roundedCorners: roundedCorners)
- drawPath(path)
- }
- }
- private enum Corner: Double {
- case TopLeft = 1
- case TopRight = 1.5
- case BottomRight = 0
- case BottomLeft = 0.5
- var startAngle: CGFloat {
- return CGFloat(rawValue * M_PI)
- }
- var endAngle: CGFloat {
- return startAngle + CGFloat(M_PI_2)
- }
- var rectCorner: UIRectCorner {
- switch self {
- case .TopLeft: return .TopLeft
- case .TopRight: return .TopRight
- case .BottomRight: return .BottomRight
- case .BottomLeft: return .BottomLeft
- }
- }
- }
- private struct Path {
- let size: CGSize
- let radius: CGFloat
- let roundedCorners: UIRectCorner
- func pointsForCorner(corner: Corner) -> (CGPoint, CGPoint?)? {
- let points: (Point, Point?)
- let width = size.width
- let height = size.height
- let rounded = roundedCorners.contains(corner.rectCorner)
- switch corner {
- case .TopLeft:
- points = rounded ? ((0, radius), (radius, radius)) : ((0, 0), nil)
- case .TopRight:
- points = rounded ? ((width - radius, 0), (width - radius, radius)) : ((width, 0), nil)
- case .BottomRight:
- points = rounded ? ((width, height - radius), (width - radius, height - radius)) : ((width, height), nil) as (Point, Point?)
- case .BottomLeft:
- points = rounded ? ((radius, height), (radius, height - radius)) : ((0, height), nil) as (Point, Point?)
- }
- return (CGPoint(x: points.0.x, y: points.0.y), points.1.map { CGPoint(x: $0.x, y: $0.y) })
- }
- }
- private extension UIBezierPath {
- func drawPath(path: Path) {
- if let (start, _) = path.pointsForCorner(.TopLeft) {
- moveToPoint(CGPoint(x: start.x, y: start.y))
- for corner: Corner in [.TopLeft, .TopRight, .BottomRight, .BottomLeft] {
- if let points = path.pointsForCorner(corner) {
- addLineToPoint(points.0)
- if let center = points.1 {
- addArcWithCenter(center, radius: path.radius, startAngle: corner.startAngle, endAngle: corner.endAngle, clockwise: true)
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement