How do you make a background image scale to screen

2019-01-05 03:12发布

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")!)

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?

9条回答
不美不萌又怎样
2楼-- · 2019-01-05 03:28

`

CGRect screenRect = [[UIScreen mainScreen] bounds];

CGFloat screenWidth = screenRect.size.width;

CGFloat screenHeight = screenRect.size.height;

_imgBackGround.frame = CGRectMake(0, 0, screenWidth, screenHeight);` 
查看更多
疯言疯语
3楼-- · 2019-01-05 03:29

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()
}
查看更多
手持菜刀,她持情操
4楼-- · 2019-01-05 03:32

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]];
查看更多
神经病院院长
5楼-- · 2019-01-05 03:36

Ahmad Fayyas Solution in Swift 3.0:

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)
}
查看更多
仙女界的扛把子
6楼-- · 2019-01-05 03:39

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. 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()
}
查看更多
劫难
7楼-- · 2019-01-05 03:46

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

查看更多
登录 后发表回答