Fabian Fabian - 1 year ago 126
Swift Question

Resize UIImage to fit device width

I need to fit an image as background in my swift 3 application. I set the background with this:

self.view.backgroundColor = UIColor(patternImage: UIImage(named: "bg_sunrise")!)

Is there a way to make sure that the image fits the current device width and is not upscaled?

dfd dfd
Answer Source

It depends on what you really want.

  • If you need "aspect fit", you need to either drop your image into a UIImageView like emresancaktar provided. The issue with this - and by your use of the view's backgroundColor you suggest this - is that you wish to put things on top of said UIImageView. This is complicating things.

  • If you just need to scale to the view size with no regard to "aspect fit", you can use it's layer:

    view.layer.contents = UIImage(named: "bg_sunrise")?.cgImage
  • Finally, if your like using a view's layer but do need "aspect fit", you'll need to work with a CGImage context, possibly using the UIImage.drawInRect() method after making some calculations. A quick search on "CALayer draw image aspect fit" yielded this gist. It's a little old but there's a Swift version there. You can cobble what you need to return a CALayer instead of a UIImage.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download