Skip to content

Instantly share code, notes, and snippets.

@sketchytech
Last active February 19, 2016 00:45
Show Gist options
  • Save sketchytech/875846f09bef426ec782 to your computer and use it in GitHub Desktop.
Save sketchytech/875846f09bef426ec782 to your computer and use it in GitHub Desktop.
Swift: Circumscribed and inscribed circles of a rect (and oval outside rect)
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)
}
}
@sketchytech
Copy link
Author

One use for this might be the masking of an image regardless of whether it is inside a view that is rectangular or square.

// image view code
let imgView = UIImageView(image: UIImage(named: "fish.jpg"))
view.addSubview(imgView)

// positioning code
imgView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true
imgView.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor).active = true
imgView.translatesAutoresizingMaskIntoConstraints = false

// masking code
let layerRect = imgView.frame
let maskingBez = UIBezierPath(inscribedCircleRect: layerRect)
let maskingLayer = CAShapeLayer()
maskingLayer.path = maskingBez.CGPath

imgView.layer.mask = maskingLayer

fish

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment