如何在swift中设置背景图片?

时间:2016-07-28 06:39:41

标签: ios swift uiimage

我正试图用快速语言将地面图像设置为我的ViewController。

我使用以下代码:

self.view.backgroundColor = UIColor(patternImage: UIImage(named:”bg.png")!)

但该应用程序正在崩溃。它显示错误,如

  

“致命错误:在打开Optional时意外发现nil   值“(因为”!“)

3 个答案:

答案 0 :(得分:19)

该错误被抛出,因为图像" bg.png"不存在。通常,当您将图像导入Assets.xcassets文件夹时,将删除文件扩展名。请尝试以下方法:

self.view.backgroundColor = UIColor(patternImage: UIImage(named:"bg")!)

您会注意到背景看起来不像预期的那样,您需要按照here的说明执行以下操作:

     UIGraphicsBeginImageContext(self.view.frame.size)
    UIImage(named: "bg")?.draw(in: self.view.bounds)
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    self.view.backgroundColor = UIColor(patternImage: image)

答案 1 :(得分:5)

试试这个Swift4:

let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "bg.png")
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(backgroundImage, at: 0)

答案 2 :(得分:1)

更新swift3:

    UIGraphicsBeginImageContext(self.frame.size)

    UIImage(named: "bg").draw(in: self.bounds)

    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!

    UIGraphicsEndImageContext()

    backgroundColor = UIColor(patternImage: image)