Skip to content

Instantly share code, notes, and snippets.

@DTHENG
Last active June 28, 2016 22:37
Show Gist options
  • Save DTHENG/b82065ef7f9654d07d352647269b0975 to your computer and use it in GitHub Desktop.
Save DTHENG/b82065ef7f9654d07d352647269b0975 to your computer and use it in GitHub Desktop.
Create a new CGRect to Fit or Fill an existing CGRect
import UIKit
extension CGRect {
func fit(width : CGFloat, height : CGFloat, fill : Bool) -> CGRect {
let isWidthGreater = width > height
let ratio = isWidthGreater ? width / height : height / width
let w = isWidthGreater ? (fill ? self.width * ratio : self.width) : (fill ? self.width : self.width / ratio)
let h = !isWidthGreater ? (fill ? self.height * ratio : self.height) : (fill ? self.height : self.height / ratio)
return CGRect(x: isWidthGreater ? (fill ? 0 - ((w - self.width) / 2) : 0) : (fill ? 0 : (self.width - w) / 2),
y: !isWidthGreater ? (fill ? 0 - ((h - self.height) / 2) : 0) : (fill ? 0 : (self.height - h) / 2),
width: w, height: h)
}
}
let rect = CGRect(x: 0, y: 0, width: 300, height: 300)
let adjustRect1 = rect.fit(90, height: 100, fill: false) // {x 15 y 0 w 270 h 300}
let adjustRect2 = rect.fit(100, height: 90, fill: false) // {x 0 y 15 w 300 h 270}
let adjustRect3 = rect.fit(90, height: 100, fill: true) // {x 0 y -16.667 w 300 h 333.333}
let adjustRect4 = rect.fit(100, height: 90, fill: true) // {x -16.667 y 0 w 333.333 h 300}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment