【Swift】UIImageのサイズを変更する
どうも、ねこきち(@nekokichi1_yos2)です。
今回は、UIImageのサイズを変更する方法を備忘録として書きます。
ソースコード
extension UIImage { func resize(size _size: CGSize) -> UIImage? { let widthRatio = _size.width / size.width let heightRatio = _size.height / size.height let ratio = widthRatio < heightRatio ? widthRatio : heightRatio let resizedSize = CGSize(width: size.width * ratio, height: size.height * ratio) UIGraphicsBeginImageContextWithOptions(resizedSize, false, 0.0) // 変更 draw(in: CGRect(origin: .zero, size: resizedSize)) let resizedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resizedImage } }
参考