图像未根据方向更改大小

时间:2018-08-18 16:33:03

标签: ios swift uiimageview

在我的应用中,我将imageView设置为这样的背景图像。

let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "backgroundView.jpg")
backgroundImage.contentMode = .scaleAspectFill
view.insertSubview(backgroundImage, at: 0)

但是当我在横向模式下旋转模拟器时,图像会被剪切掉。 附言我还注意到,如果我在横向运行我的应用程序,则即使我旋转到纵向和纵向也非常适合。 enter image description here

1 个答案:

答案 0 :(得分:1)

代替框架

let backgroundImage = UIImageView(frame: UIScreen.main.bounds)

您需要使用自动布局

let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.translatesAutoresizingMaskIntoConstraints = false
backgroundImage.image = UIImage(named: "backgroundView.jpg")
backgroundImage.contentMode = .scaleAspectFill
view.insertSubview(backgroundImage, at: 0)
NSLayoutConstraint.activate([
    backgroundImage.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant:0),
    backgroundImage.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:0),
    backgroundImage.topAnchor.constraint(equalTo: view.topAnchor,constant:0),
    backgroundImage.bottomAnchor.constraint(equalTo: view.bottomAnchor,constant:0) 
])