LoginSignup
0
1

More than 5 years have passed since last update.

UIImageを縮小率に応じてリサイズする

Last updated at Posted at 2018-07-27

overview

(小ネタです)

UIImageViewではなくUIImageの段階でリサイズしたい状況、まれにあったりする。
そのような時は、以下のようなExtensionで対応できる。

detail

UIImage+Resize.swift
import UIKit

protocol ImageResizing {
    func resize(with ratioType: UIImage.ResizeRatioType) -> UIImage!
}

extension UIImage: ImageResizing {
    enum ResizeRatioType {
        case naviIconSize
        case tabIconSize

        var ratio: CGFloat {
            switch self {
            case .naviIconSize:
                return 0.9
            case .tabIconSize:
                return 0.75
            }
        }
    }

    func resize(with ratioType: UIImage.ResizeRatioType) -> UIImage! {
        return resize(
            with: CGSize(
                width: size.width * ratioType.ratio,
                height: size.height * ratioType.ratio
            )
        )
    }

    // MARK: - private
    private func resize(with newSize: CGSize) -> UIImage! {
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
}

注意点

scale
The scale factor to apply to the bitmap. If you specify a value of 0.0, the scale factor is set to the scale factor of the device’s main screen.

UIGraphicsBeginImageContextWithOptions(::_:) - Apple Developer

上記の通りで、Asset Catalogなどを利用しているのであれば UIGraphicsBeginImageContextWithOptions の第三引数 scale に0.0を渡しておく。
(これにより常に使用デバイスのメインスクリーンスケールが適用される)

usage

通常:

let image = UIImage(named: "star")?.resize(with: .naviIconSize)

Asset catalogから直に呼ぶ場合:

スクリーンショット 2018-07-28 6.30.11.png

SwiftGenの場合:

let image = Asset.MaterialIcon.icClose36pt.image.resize(with: .naviIconSize)

おまけ

使い道は?

  • こういったものを元データには手を入れずにリサイズしたいときとか
  • UIBarButtonItem など直接UIImageViewをいじりづらいときとかに、シュッと使うと吉
0
1
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
1