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

前端 未结 9 2085
刺人心
刺人心 2020-11-27 04:27

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 scr

相关标签:
9条回答
  • 2020-11-27 04:49

    Just add your UIImageView positioned centered and with all edges snapping to the edges. 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.

    enter image description here

    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:

    enter image description here

    0 讨论(0)
  • 2020-11-27 04:57

    Here are your options for scaling!

    For the .contentMode property:

    ScaleToFill This will scale the image inside the image view to fill the entire boundaries of the image view.

    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.

    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. For this value to work properly, make sure that you have set the clipsToBounds property of the imageview to 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)
    
    0 讨论(0)
  • 2020-11-27 04:57

    For this, I think you'll need to create a UIImageView that is pinned to the parent views top / bottom / left / right. This will make the UIImageView always the match the size of the display. Just make sure you set the content mode on the imageview to be 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]];
    
    0 讨论(0)
  • 2020-11-27 04:59

    This uses PureLayout. You could just use AutoLayout with a few more lines.

    UIImageView* imgView = UIImageView(image: myUIImage)
    imgView.setTranslatesAutoresizingMaskIntoConstraints(false)
    self.view.addSubview(imgView)
    self.view.addConstraints(imgView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(0,0,0,0))
    
    0 讨论(0)
  • 2020-11-27 05:03

    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:

    Remember: if you are adding it in a new .swift file, remember to add 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
    0 讨论(0)
  • 2020-11-27 05:05

    I used constraints to make the image "autoLayout". I made a view to show an activity indicator (with full background image), while the view on segue is loading. 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.

    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". 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.

    To remove the view, after the lazy loading, just use the code below.

    private func hideActivityIndicator() {
        actionIndicator.stopAnimating()
        containerView.removeFromSuperview()
    }
    
    0 讨论(0)
提交回复
热议问题