ios - 如何根据给定的边界/容器使 UIImageView 具有正方形大小

标签 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 并调整其父 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/

相关文章:

ios - ScrollView 中的一种方式分页

swift - 将 [NSURL] 转换为 NSUserDefaults 的 [String]?

ios - 如何在单击“取消”按钮时关闭 UIActivityViewController?

objective-c - Xcode 和检查代码约定

ios - 如何在 Xcode 中签署存档应用程序

ios - 不会将图像传递到目标 ViewController

ios - 在 AppDelegate 中使用条件登录

objective-c - AppDelegate 中的方向检测

iOS 版本构建崩溃 : TypeError: n. 渲染不是一个函数。 (在 'n.render()' 中, 'n.render' 未定义)React Native 0.56

ios - Titanium - 无法为设备构建(com.apple.syslog_relay 错误)