LoginSignup
0
2

More than 1 year has passed since last update.

UIImageの画像の大きさを変えるExtension(拡張)を作る

Posted at

結論から書くとこんな感じ。

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の練習も兼ねて行ったためです。

誰かの参考になれば幸いです。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2