Last active
February 19, 2016 00:45
-
-
Save sketchytech/875846f09bef426ec782 to your computer and use it in GitHub Desktop.
Swift: Circumscribed and inscribed circles of a rect (and oval outside rect)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension CGFloat { | |
func radians() -> CGFloat { | |
let b = CGFloat(M_PI) * (self/180) | |
return b | |
} | |
} | |
extension UIBezierPath { | |
convenience init(circumscribedCircleRect rect:CGRect) { | |
let halfWidth = rect.width / 2 | |
let halfHeight = rect.height / 2 | |
let radius = sqrt(halfWidth * halfWidth + halfHeight * halfHeight) | |
let center = CGPointMake(rect.midX, rect.midY) | |
self.init(arcCenter: center, radius: radius, startAngle: CGFloat(0).radians(), endAngle: CGFloat(360).radians(), clockwise: true) | |
} | |
convenience init(inscribedCircleRect rect:CGRect) { | |
let halfWidth = rect.width / 2 | |
let halfHeight = rect.height / 2 | |
let radius = halfWidth >= halfHeight ? halfHeight : halfWidth | |
let center = CGPointMake(rect.midX, rect.midY) | |
self.init(arcCenter: center, radius: radius, startAngle: CGFloat(0).radians(), endAngle: CGFloat(360).radians(), clockwise: true) | |
} | |
convenience init(ovalOutsideRect rect:CGRect) { | |
let width = rect.width | |
let height = rect.height | |
let origin = CGPointMake(rect.minX, rect.minY) | |
let newSize = CGSizeMake(CGFloat(M_SQRT2) * width, CGFloat(M_SQRT2) * height) | |
let newRect = CGRect(x: origin.x + (width - newSize.width) / 2, y: origin.y + (height - newSize.height) / 2, width: newSize.width, height: newSize.height) | |
self.init(ovalInRect:newRect) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One use for this might be the masking of an image regardless of whether it is inside a view that is rectangular or square.