所以我正在尝试创建一个简单的 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 并调整其父 View 的大小以使图片成为正方形。
最佳答案
应该这样做(并将 ImageView 置于包含 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)
}
关于ios - 如何根据给定的边界/容器使 UIImageView 具有正方形大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53078695/