Search code examples
iosswiftrotationuiimagegetimagesize

How do you display an image at the maximum available space?


I check if the image is vertical or horizontal. If it is horizontal, I rotate it:

@IBOutlet private weak var img: UIImageView!

img.image = file.image    
let imageSize = file.image?.size
let imgWidth = imageSize?.width ?? 0
let imgHeight = imageSize?.height ?? 0
                    
if imgWidth > imgHeight {
    print("IMG HORIZONTAL")
    imgDetail.transform = imgDetail.transform.rotated(by: .pi / 2)
} else {
    print("IMG VERTICAL")
}

But it leaves me a space around the image. I would like it to be at the maximum size of the UIImageView.

enter image description here

enter image description here


Solution

  • Try this, declare your imageView:

    let YourImageView: UIImageView = {
        let iv = UIImageView()
        iv.image = UIImage(named: "myImage")?.withRenderingMode(.alwaysOriginal)
        iv.backgroundColor = .clear
        iv.contentMode = .scaleAspectFit
        iv.isUserInteractionEnabled = true
        iv.clipsToBounds = true
        iv.translatesAutoresizingMaskIntoConstraints = false
        
        return iv
    }()
    

    in viewDidLoad set if statement and call setupConstraints:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        view.backgroundColor = .white
        
        guard let imgWidth = YourImageView.image?.size.width else { return }
        guard let imgHeight = YourImageView.image?.size.height else { return }
    
        if imgWidth > imgHeight {
            print("IMG HORIZONTAL")
            guard let image = YourImageView.image else { return }
            let newImage = image.rotate(radians: .pi / 2) // image rotation
            YourImageView.image = newImage
        } else {
            print("IMG VERTICAL")
        }
        
        setupConstraints()
    }
    

    set up constraints

    fileprivate func setupConstraints() {
        
        view.addSubview(YourImageView)
        YourImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        YourImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        YourImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        YourImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    }
    

    write image extension

    extension UIImage {
    func rotate(radians: Float) -> UIImage? {
        var newSize = CGRect(origin: CGPoint.zero, size: self.size).applying(CGAffineTransform(rotationAngle: CGFloat(radians))).size
        // Trim off the extremely small float value to prevent core graphics from rounding it up
        newSize.width = floor(newSize.width)
        newSize.height = floor(newSize.height)
    
        UIGraphicsBeginImageContextWithOptions(newSize, false, self.scale)
        guard let context = UIGraphicsGetCurrentContext() else { return UIImage()}
    
        // Move origin to middle
        context.translateBy(x: newSize.width/2, y: newSize.height/2)
        // Rotate around middle
        context.rotate(by: CGFloat(radians))
        // Draw the image at its center
        self.draw(in: CGRect(x: -self.size.width/2, y: -self.size.height/2, width: self.size.width, height: self.size.height))
    
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    
        return newImage
     }
    }
    

    this is the result normal (without image rotate extension call) and rotated (with image rotate extension call):

    enter image description here