ios 如何快速设置背景图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38628803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:47:05  来源:igfitidea点击:

How to set background image in swift?

iosswiftuiimage

提问by anusha hrithi

I am trying to set aground image to my ViewController in swift language.

我正在尝试以 swift 语言将搁浅图像设置到我的 ViewController 中。

I am using the following code :

我正在使用以下代码:

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

But the app is getting crash.It is showing the error like

但是应用程序崩溃了。它显示的错误如下

“fatal error: unexpectedly found nil while unwrapping an Optional value”(Because of the “!”)

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

回答by drdrdrdr

That error is thrown because the image "bg.png" does not exist. Usually when you import images to the Assets.xcassets folder, the file extension is removed. So try the following:

抛出该错误是因为图像“bg.png”不存在。通常,当您将图像导入 Assets.xcassets 文件夹时,会删除文件扩展名。因此,请尝试以下操作:

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

You will notice that the background will not look as expected, you need to do the following as explained 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)

回答by Arafin Russell

Try this Swift4:

试试这个 Swift4:

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

回答by Fares Ben Hamouda

Update for swift3 :

swift3 的更新:

    UIGraphicsBeginImageContext(self.frame.size)

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

    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!

    UIGraphicsEndImageContext()

    backgroundColor = UIColor(patternImage: image)