Advertisement
Guest User

Untitled

a guest
Oct 6th, 2015
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. import Darwin
  2.  
  3. private typealias Point = (x: CGFloat, y: CGFloat)
  4.  
  5. extension UIBezierPath {
  6. public convenience init(rect: CGRect, cornerRadius radius: CGFloat, roundedCorners: UIRectCorner = .AllCorners) {
  7. self.init()
  8. let path = Path(size: rect.size, radius: radius, roundedCorners: roundedCorners)
  9. drawPath(path)
  10. }
  11. }
  12.  
  13. private enum Corner: Double {
  14. case TopLeft = 1
  15. case TopRight = 1.5
  16. case BottomRight = 0
  17. case BottomLeft = 0.5
  18.  
  19. var startAngle: CGFloat {
  20. return CGFloat(rawValue * M_PI)
  21. }
  22.  
  23. var endAngle: CGFloat {
  24. return startAngle + CGFloat(M_PI_2)
  25. }
  26.  
  27. var rectCorner: UIRectCorner {
  28. switch self {
  29. case .TopLeft: return .TopLeft
  30. case .TopRight: return .TopRight
  31. case .BottomRight: return .BottomRight
  32. case .BottomLeft: return .BottomLeft
  33. }
  34. }
  35. }
  36.  
  37. private struct Path {
  38. let size: CGSize
  39. let radius: CGFloat
  40. let roundedCorners: UIRectCorner
  41.  
  42. func pointsForCorner(corner: Corner) -> (CGPoint, CGPoint?)? {
  43. let points: (Point, Point?)
  44. let width = size.width
  45. let height = size.height
  46. let rounded = roundedCorners.contains(corner.rectCorner)
  47.  
  48. switch corner {
  49. case .TopLeft:
  50. points = rounded ? ((0, radius), (radius, radius)) : ((0, 0), nil)
  51. case .TopRight:
  52. points = rounded ? ((width - radius, 0), (width - radius, radius)) : ((width, 0), nil)
  53. case .BottomRight:
  54. points = rounded ? ((width, height - radius), (width - radius, height - radius)) : ((width, height), nil) as (Point, Point?)
  55. case .BottomLeft:
  56. points = rounded ? ((radius, height), (radius, height - radius)) : ((0, height), nil) as (Point, Point?)
  57. }
  58.  
  59. return (CGPoint(x: points.0.x, y: points.0.y), points.1.map { CGPoint(x: $0.x, y: $0.y) })
  60. }
  61. }
  62.  
  63. private extension UIBezierPath {
  64. func drawPath(path: Path) {
  65. if let (start, _) = path.pointsForCorner(.TopLeft) {
  66. moveToPoint(CGPoint(x: start.x, y: start.y))
  67. for corner: Corner in [.TopLeft, .TopRight, .BottomRight, .BottomLeft] {
  68. if let points = path.pointsForCorner(corner) {
  69. addLineToPoint(points.0)
  70. if let center = points.1 {
  71. addArcWithCenter(center, radius: path.radius, startAngle: corner.startAngle, endAngle: corner.endAngle, clockwise: true)
  72. }
  73. }
  74. }
  75. }
  76. }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement