如何快速将背景图像缩放到屏幕大小? [英] How do you make a background image scale to screen size in swift?

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

问题描述

我正在尝试使用图案图像快速为我的背景制作 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 extension(文件-> 新建 -> 文件 -> 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()
}

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

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