如何快速设置背景图像? [英] How to set background image in swift?

查看:47
本文介绍了如何快速设置背景图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以快速的语言为ViewController设置搁浅的图像.

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

我正在使用以下代码:

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

但是应用程序崩溃了,它显示了类似的错误

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

致命错误:解开Optional时意外发现nil值"(因为!")

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

推荐答案

由于图像"bg.png"不存在而引发该错误.通常,当您将图像导入Assets.xcassets文件夹时,文件扩展名将被删除.因此,请尝试以下操作:

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:

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)

这篇关于如何快速设置背景图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆