Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 834
GuiGui23 Avatar asked Nov 26 '14 15:11

GuiGui23


People also ask

How do I change the size of an image in Swift?

Image resize function in swift as below. func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage { let size = image. size let widthRatio = targetSize. width / size.

How do I fit an image in Swift UI?

To make an image scales to fit the current view, we use the resizable() modifier, which resizes an image to fit available space. We can see the whole image now, but it got stretched out and losing its aspect ratio, which is usually not the behavior we want. The image view resize to fit available space.

How do you put a background picture on storyboard?

Go to 'View->Show Library' and choose the Image View and drag it to the middle of the screen until it snaps perfectly in the center. This Image View will serve as the background image and it will fill the entire screen, including the area past the safe area view.


1 Answers

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() } 
like image 139
Ahmad Fayyas Avatar answered Oct 09 '22 03:10

Ahmad Fayyas