1
votes

So I am trying to create a simple UIImageView to make it have a square frame/size with CGSize. Based on a given bounds. So for example if the bounds container is the width & height of the screen then. The function should resize the UIImageView to fit like a perfect square base on those bounds on the screen.

Code:

let myImageView = UIImageView()
myImageView.frame.origin.y = (self.view?.frame.height)! * 0.0
myImageView.frame.origin.x = (self.view?.frame.width)! * 0.0
myImageView.backgroundColor = UIColor.blue
self.view?.insertSubview(myImageView, at: 0)

//("self.view" is the ViewController view that is the same size as the devices screen)

MakeSquare(view: myImageView, boundsOf: self.view)




func MakeSquare(view passedview: UIImageView, boundsOf container: UIView) {

let ratio = container.frame.size.width / container.frame.size.height

if container.frame.width > container.frame.height {
    let newHeight = container.frame.width / ratio
    passedview.frame.size = CGSize(width: container.frame.width, height: newHeight)
} else{
    let newWidth = container.frame.height * ratio
    passedview.frame.size = CGSize(width: newWidth, height: container.frame.height)
 }
}

The problem is its giving me back the same bounds/size of the container & not changed

Note: I really have know idea how to pull this off, but wanted to see if its possible. My function comes from a question here. That takes a UIImage and resizes its parent view to make the picture square.

1

1 Answers

2
votes

This should do it (and will centre the image view in the containing view):

func makeSquare(view passedView: UIImageView, boundsOf container: UIView) {
    let minSize = min(container.bounds.maxX, container.bounds.maxY)
    passedView.bounds = CGRect(x: container.bounds.midX - minSize / 2.0, 
        y: container.bounds.midY - minSize / 2.0, 
        width: minSize, height: minSize)
}