Created
December 24, 2023 18:41
-
-
Save StewartLynch/683d19ed0cd9fb600607da0b6f99aa49 to your computer and use it in GitHub Desktop.
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
import UIKit | |
extension UIImage { | |
func resizeImage(targetSize: CGSize) -> UIImage { | |
let size = self.size | |
let widthRatio = targetSize.width / size.width | |
let heightRatio = targetSize.height / size.height | |
let newSize = widthRatio > heightRatio ? CGSize(width: size.width * heightRatio, height: size.height * heightRatio) : CGSize(width: size.width * widthRatio, height: size.height * widthRatio) | |
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) | |
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) | |
self.draw(in: rect) | |
let newImage = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return newImage! | |
} | |
func resized(toWidth width: CGFloat) -> UIImage? { | |
let canvasSize = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height))) | |
UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale) | |
defer { UIGraphicsEndImageContext() } | |
draw(in: CGRect(origin: .zero, size: canvasSize)) | |
return UIGraphicsGetImageFromCurrentImageContext() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment