如何在swift中将背景图像缩放到屏幕尺寸? [英] How do you make a background image scale to screen size in swift?
问题描述
我正在尝试使用模式图像在swift中为我的背景制作UIView图像。我的代码运行良好,除了我希望图像占据整个屏幕的事实。我的代码如下所示: self.view.backgroundColor = UIColor(patternImage:UIImage(named:backgroundImage)!)
I'm trying to make a UIView image for my background in swift using pattern image. The code I have works well except for the fact that I want the image to take the whole screen. My code looks like this: self.view.backgroundColor = UIColor(patternImage: UIImage(named: "backgroundImage")!)
有谁知道如何使背景成为占据整个屏幕的图像,并且在出现在不同的iPhone屏幕尺寸时会缩放?
Does anyone know how to make the background an image that will take up the whole screen, and would scale when appearing on different iPhone screen sizes?
推荐答案
注意:
我从我的旧帐户发布了这个答案(对我来说已弃用,我无法访问它这是我的改进的答案。
您可以通过编程方式执行此操作,而不是在每个视图中创建IBOutlet。
只需创建一个UIView 扩展(文件 - >新建 - >文件 - > Swift文件 - >根据需要命名)并添加:
You can do it programmatically instead of creating an IBOutlet in each view. just create a UIView extension (File -> New -> File -> Swift File -> name it whatever you want) and add:
extension UIView {
func addBackground() {
// screen width and height:
let width = UIScreen.mainScreen().bounds.size.width
let height = UIScreen.mainScreen().bounds.size.height
let imageViewBackground = UIImageView(frame: CGRectMake(0, 0, width, height))
imageViewBackground.image = UIImage(named: "YOUR IMAGE NAME GOES HERE")
// you can change the content mode:
imageViewBackground.contentMode = UIViewContentMode.ScaleAspectFill
self.addSubview(imageViewBackground)
self.sendSubviewToBack(imageViewBackground)
}}
现在,您可以将此方法与您的方法一起使用观点,为示例:
Now, you can use this method with your views, for example:
override func viewDidLoad() {
super.viewDidLoad()
self.view.addBackground()
}
这篇关于如何在swift中将背景图像缩放到屏幕尺寸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!