2018-02-17 15:14:53 +00:00
|
|
|
import Foundation
|
|
|
|
import UIKit
|
2015-06-09 21:28:11 +00:00
|
|
|
extension CGSize {
|
|
|
|
/// Calculates the aspect ratio of the size.
|
|
|
|
///
|
|
|
|
/// - returns: aspectRatio The aspect ratio of the size.
|
|
|
|
var aspectRatio: CGFloat {
|
|
|
|
if height == 0 { return 1 }
|
|
|
|
return width / height
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Finds a new size constrained by a size keeping the aspect ratio.
|
|
|
|
///
|
|
|
|
/// - parameter size: The contraining size.
|
|
|
|
/// - returns: size A new size that fits inside the contraining size with the same aspect ratio.
|
2016-06-18 22:56:52 +00:00
|
|
|
func constrained(by size: CGSize) -> CGSize {
|
2015-06-09 21:28:11 +00:00
|
|
|
let aspectWidth = round(aspectRatio * size.height)
|
|
|
|
let aspectHeight = round(size.width / aspectRatio)
|
|
|
|
|
|
|
|
if aspectWidth > size.width {
|
|
|
|
return CGSize(width: size.width, height: aspectHeight)
|
|
|
|
} else {
|
|
|
|
return CGSize(width: aspectWidth, height: size.height)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Finds a new size filling the given size while keeping the aspect ratio.
|
|
|
|
///
|
|
|
|
/// - parameter size: The contraining size.
|
|
|
|
/// - returns: size A new size that fills the contraining size keeping the same aspect ratio.
|
2016-10-01 11:41:22 +00:00
|
|
|
func filling(_ size: CGSize) -> CGSize {
|
2015-06-09 21:28:11 +00:00
|
|
|
let aspectWidth = round(aspectRatio * size.height)
|
|
|
|
let aspectHeight = round(size.width / aspectRatio)
|
|
|
|
|
|
|
|
if aspectWidth > size.width {
|
|
|
|
return CGSize(width: aspectWidth, height: size.height)
|
|
|
|
} else {
|
|
|
|
return CGSize(width: size.width, height: aspectHeight)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|