結論から書くとこんな感じ。
import UIKit
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 resizeSize = CGSize(width: size.width * ratio, height: size.height * ratio)
UIGraphicsBeginImageContextWithOptions(resizeSize, false, 0.0)
draw(in: CGRect(origin: .zero, size: resizeSize))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resizedImage
}
}
使い方
class BottomButtonView: UIView {
var button: UIButton?
init(frame: CGRect, width: CGFloat) {
super.init(frame: frame)
button = UIButton(type: .system)
// ↓これ
button?.setImage(UIImage(named: "")?.resize(size: .init(width: width * 0.4, height: width * 0.4)), for: .normal)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
拡張機能なので、元々UIImageで準備されている関数に欲しい関数がなかったので新しく関数を加えました。
class BottomButtonView: UIViewみたいな感じでUIViewのクラスを作成しているのは、storyboardなしでMVVMの練習も兼ねて行ったためです。
誰かの参考になれば幸いです。