Putting this as an answer, as well as an example use ...
The scaling code is not mine, it is: https://gist.github.com/tomasbasham/10533743#gistcomment-1988471
Here is the code that you can run on the playground for testing:
import UIKit
import PlaygroundSupport
let container = UIView(frame: CGRect(x: 0, y: 0, width: 800, height: 800))
container.backgroundColor = UIColor.blue
PlaygroundPage.current.liveView = container
extension UIImage {
enum ScalingMode {
case aspectFill
case aspectFit
func aspectRatio(between size: CGSize, and otherSize: CGSize) -> CGFloat {
let aspectWidth = size.width/otherSize.width
let aspectHeight = size.height/otherSize.height
switch self {
case .aspectFill:
return max(aspectWidth, aspectHeight)
case .aspectFit:
return min(aspectWidth, aspectHeight)
}
}
}
func scaled(to newSize: CGSize, scalingMode: UIImage.ScalingMode = .aspectFill) -> UIImage {
let aspectRatio = scalingMode.aspectRatio(between: newSize, and: size)
var scaledImageRect = CGRect.zero
scaledImageRect.size.width = size.width * aspectRatio
scaledImageRect.size.height = size.height * aspectRatio
scaledImageRect.origin.x = (newSize.width - size.width * aspectRatio) / 2.0
scaledImageRect.origin.y = (newSize.height - size.height * aspectRatio) / 2.0
UIGraphicsBeginImageContext(newSize)
draw(in: scaledImageRect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
}
if let srcimg = UIImage(named: "flags") {
let w = srcimg.size.width
let h = srcimg.size.height
let longer = max(w, h)
let sz = CGSize(width: longer, height: longer)
let newImage = srcimg.scaled(to: sz, scalingMode: .aspectFit)
let v = UIImageView(image: newImage)
v.backgroundColor = UIColor.white
container.addSubview(v)
}
source
share