简体   繁体   English

如何快速将背景图像缩放到屏幕尺寸?

[英]How do you make a background image scale to screen size in swift?

I'm trying to make a UIView image for my background in swift using pattern image. 我正在尝试使用模式图像快速制作背景的UIView图像。 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")!) 我的代码如下所示: self.view.backgroundColor = UIColor(patternImage: UIImage(named: "backgroundImage")!)

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? 有谁知道如何使背景图像占据整个屏幕,并且在不同的iPhone屏幕尺寸上显示时会缩放?

Note That: 注意:

I posted this answer from my old account (which is deprecated for me and I can't access it anymore), this is my improved answer . 我从我的旧帐户中发布了此答案(该帐户已被我淘汰,现在无法使用了),这是我的改进答案


You can do it programmatically instead of creating an IBOutlet in each view. 您可以以编程方式执行此操作,而不是在每个视图中创建IBOutlet。 just create a UIView extension (File -> New -> File -> Swift File -> name it whatever you want) and add: 只需创建一个UIView 扩展 (文件->新建->文件-> Swift文件->随意命名)并添加:

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()
}

Just add your UIImageView positioned centered and with all edges snapping to the edges. 只需将UIImageView添加到居中位置,并将所有边缘对齐到边缘即可。 Leave it there and click on the right bottom corner as shown below and now go ahead and add 4 constrains to Top, Bottom, Left and Right Edges. 将其保留在此处,然后单击右下角,如下所示,然后继续并在“顶部”,“底部”,“左边缘”和“右边缘”上添加4个约束。

在此处输入图片说明

Now just select your image view and using the IB inspector select how you would like your image: fill or fit as you can see as follow: 现在,只需选择您的图像视图,然后使用IB检查器选择您想要的图像:填充或调整如下所示:

在此处输入图片说明

This is the updated answer of my previous one . 这是我上一个的最新答案。

As the same approach of my previous answer, You can create an extension of UIView and add addBackground() method to it, as follows: 与我以前的答案相同,可以创建UIView的扩展并将addBackground()方法添加到其中,如下所示:

Remember: if you are adding it in a new .swift file, remember to add import UIKit 记住:如果要将其添加到新的.swift文件中,请记住添加import UIKit

extension UIView {
    func addBackground(imageName: String = "YOUR DEFAULT IMAGE NAME", contentMode: UIView.ContentMode = .scaleToFill) {
        // setup the UIImageView
        let backgroundImageView = UIImageView(frame: UIScreen.main.bounds)
        backgroundImageView.image = UIImage(named: imageName)
        backgroundImageView.contentMode = contentMode
        backgroundImageView.translatesAutoresizingMaskIntoConstraints = false

        addSubview(backgroundImageView)
        sendSubviewToBack(backgroundImageView)

        // adding NSLayoutConstraints
        let leadingConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0.0)
        let trailingConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0.0)
        let topConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0)
        let bottomConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0.0)

        NSLayoutConstraint.activate([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])
    }
}

Note that the updates for this answer are: 请注意,此答案的更新为:

  • Swift 4 code 🙂 Swift 4代码🙂
  • Adding -programatically- NSLayoutConstraints : that's because when applying what's mentioned in my previous answer, it works fine for the current device orientation, but not when the application does support both portrait/landscape modes, if the device orientation has been changed, the background imageView size will be the same (same size) and not adapts the new width/height of the device screen, so adding constraints should solve this issue. 添加-programatically- NSLayoutConstraints:那是因为采用什么在我以前的答复时提到,它工作正常,当前设备的方向,而不是在该应用程序支持纵向/横向模式下,如果设备的方向已经改变,后台的ImageView大小将相同(相同大小),并且不会适应设备屏幕的新宽度/高度,因此添加约束应该可以解决此问题。
  • Adding default parameters: for more flexibility, you might -sometimes- want to change the default image or even the context mode for you background: 添加默认参数:为了获得更大的灵活性,您有时可能希望更改默认图像或什至背景的上下文模式:

Usage: 用法:

Assuming that you want to call it in viewDidLoad() : 假设您要在viewDidLoad()调用它:

override func viewDidLoad() {
    //...

    // you can call 4 versions of addBackground() method

    // 1- this will add it with the default imageName and default contextMode
    view.addBackground()

    // 2- this will add it with the edited imageName and default contextMode
    view.addBackground(imageName: "NEW IMAGE NAME")

    // 3- this will add it with the default imageName and edited contextMode
    view.addBackground(contentMode: .scaleAspectFit)

    // 4- this will add it with the default imageName and edited contextMode
    view.addBackground(imageName: "NEW IMAGE NAME", contextMode: .scaleAspectFit)
}

Here are your options for scaling! 这是您扩展的选项!

For the .contentMode property: 对于.contentMode属性:

ScaleToFill This will scale the image inside the image view to fill the entire boundaries of the image view. ScaleToFill这将缩放图像视图内的图像以填充图像视图的整个边界。

ScaleAspectFit This will make sure the image inside the image view will have the right aspect ratio and fit inside the image view's boundaries. ScaleAspectFit这将确保图像视图内的图像具有正确的宽高比并适合图像视图的边界。

ScaleAspectFill This will make sure the image inside the image view will have the right aspect ratio and fill the entire boundaries of the image view. ScaleAspectFill这将确保图像视图内的图像具有正确的宽高比并填充图像视图的整个边界。 For this value to work properly, make sure that you have set the clipsToBounds property of the imageview to true. 为了使此值正常工作,请确保已将imageview的clipsToBounds属性设置为true。

class SecondViewController : UIViewController {

    let backgroundImage = UIImage(named: "centralPark")
    var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.thirdChoiceField.delegate = self
        self.datePicker.minimumDate = NSDate()
        imageView = UIImageView(frame: view.bounds)
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        imageView.image = backgroundImage
        imageView.center = view.center
        view.addSubview(imageView)
        self.view.sendSubviewToBack(imageView)

This uses PureLayout . 这使用PureLayout You could just use AutoLayout with a few more lines. 您可以只使用AutoLayout多行。

UIImageView* imgView = UIImageView(image: myUIImage)
imgView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(imgView)
self.view.addConstraints(imgView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(0,0,0,0))

I used constraints to make the image "autoLayout". 我使用约束使图像成为“ autoLayout”。 I made a view to show an activity indicator (with full background image), while the view on segue is loading. 我正在查看显示活动指示器(带有完整的背景图片)的视图,同时正在加载有关segue的视图。 The code is as follows. 代码如下。

var containerView: UIView = UIView()
var actionIndicator: UIActivityIndicatorView = UIActivityIndicatorView()

private func showActivityIndicator() {
    ///first I set the containerView and the background image
    containerView.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(containerView)
    adjustConstFullSize(containerView, parentView: self.view)
    let backImage = UIImageView(image: UIImage(named: "AppBackImage"))
    backImage.contentMode = UIViewContentMode.ScaleAspectFill
    backImage.translatesAutoresizingMaskIntoConstraints = false
    containerView.addSubview(backImage)
    adjustConstFullSize(backImage, parentView: containerView)

    ////setting the spinner (activity indicator)
    actionIndicator.frame = CGRectMake(0.0, 0.0, 40.0, 40.0)
    actionIndicator.center = CGPointMake(containerView.bounds.size.width / 2, containerView.bounds.size.height / 2)
    actionIndicator.hidesWhenStopped = true
    actionIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
    containerView.insertSubview(actionIndicator, aboveSubview: backImage)

    ///throw the container to the main view
    view.addSubview(containerView)
    actionIndicator.startAnimating()
}

This is the code for the "adjustConstFullSize" function. 这是“ adjustConstFullSize”函数的代码。

func adjustConstFullSize(adjustedView: UIView!, parentView: UIView!) {
    let topConstraint = NSLayoutConstraint(item: adjustedView,
        attribute: .Top,
        relatedBy: .Equal,
        toItem: parentView,
        attribute: .Top,
        multiplier: 1.0,
        constant: 0.0)

    let leftConstraint = NSLayoutConstraint(item: adjustedView,
        attribute: .Leading,
        relatedBy: .Equal,
        toItem: parentView,
        attribute: .Leading,
        multiplier: 1.0,
        constant: 0.0)

    let rightConstraint = NSLayoutConstraint(item: adjustedView,
        attribute: .Trailing,
        relatedBy: .Equal,
        toItem: parentView,
        attribute: .Trailing,
        multiplier: 1.0,
        constant: 0.0)


    let bottomConstraint = NSLayoutConstraint(item: adjustedView,
        attribute: .Bottom,
        relatedBy: .Equal,
        toItem: parentView,
        attribute: .Bottom,
        multiplier: 1.0,
        constant: 0.0)

    parentView.addConstraints([topConstraint, leftConstraint, rightConstraint, bottomConstraint])
}

In the function shown above, I "tied" the containerView constraints to the main view constraints, making the view "full size". 在上面显示的函数中,我将containerView约束“绑定”到主视图约束,使视图“全尺寸”。 I did the same for the UIImageView and also set the contentMode to AspectFill - this is crucial, because we want the image to fill the content without stretching. 我对UIImageView进行了相同的操作,并将contentMode设置为AspectFill-这很关键,因为我们希望图像填充内容而不会拉伸。

To remove the view, after the lazy loading, just use the code below. 要删除视图,请在延迟加载后使用下面的代码。

private func hideActivityIndicator() {
    actionIndicator.stopAnimating()
    containerView.removeFromSuperview()
}

Ahmad Fayyas Solution in Swift 3.0 : Swift 3.0中的Ahmad Fayyas解决方案

func addBackground() {
    let width = UIScreen.main.bounds.size.width
    let height = UIScreen.main.bounds.size.height

    let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width: width, height: height))
    imageViewBackground.image = UIImage(named: "YOUR IMAGE NAME GOES HERE")

    // you can change the content mode:
    imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill

    self.view.addSubview(imageViewBackground)
    self.view.sendSubview(toBack: imageViewBackground)
}

For this, I think you'll need to create a UIImageView that is pinned to the parent views top / bottom / left / right. 为此,我认为您需要创建一个UIImageView并将其固定在父视图的顶部/底部/左侧/右侧。 This will make the UIImageView always the match the size of the display. 这将使UIImageView始终与显示的大小匹配。 Just make sure you set the content mode on the imageview to be AspectFit 只要确保将imageview的内容模式设置为AspectFit

var newImgThumb : UIImageView
newImgThumb = UIImageView(view.bounds)
newImgThumb.contentMode = .ScaleAspectFit
view.addSubview(newImgThumb)

//Don't forget this line
newImgThumb.setTranslatesAutoresizingMaskIntoConstraints(false)

NSDictionary *views =NSDictionaryOfVariableBindings(newImgThumb);


// imageview fills the width of its superview
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[newImgThumb]|" options:0 metrics:metrics views:views]];
// imageview fills the height of its superview
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[newImgThumb]|" options:0 metrics:metrics views:views]];

` `

CGRect screenRect = [[UIScreen mainScreen] bounds];

CGFloat screenWidth = screenRect.size.width;

CGFloat screenHeight = screenRect.size.height;

_imgBackGround.frame = CGRectMake(0, 0, screenWidth, screenHeight);` 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM