如何使UIImageView具有基于给定范围/容器的正方形大小

时间:2018-10-31 07:55:43

标签: ios swift xcode uiview

所以我试图创建一个简单的UIImageView使其具有CGSize的正方形框架/大小。基于给定范围。因此,例如,如果边界容器是屏幕的宽度和高度,那么。该功能应调整UIImageView的大小,使其适合屏幕上边界的完美正方形。

代码:

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)
 }
}

问题是它给了我相同的容器边界/大小,并且没有改变

注意:我确实知道如何实现此目标,但想知道是否可行。我的功能来自问题here。这需要一个UIImage并调整其父视图的大小以使图片变为正方形。

1 个答案:

答案 0 :(得分:1)

这应该做到(并将图像视图在包含的视图中居中):

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)
}