How do I center and aspect fit an image in Swift 3?

Tanner Helton picture Tanner Helton · Feb 17, 2017 · Viewed 16.7k times · Source

I have a project in Swift 3 that I am using a gradient on the view. I placed a image on the view, but it is under the gradient layer so I was going to draw the image programmatically instead of with the storyboard. I can't seem to figure out how to get the image to be centered and to aspect fit inside the bounds of the view.

What I have...

//Gradient Background
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.view.frame
gradientLayer.colors = [UIColor(red: 0/255, green: 147/255, blue: 255/255, alpha: 1.0).cgColor, UIColor(red: 162/255, green: 134/255, blue: 255/255, alpha: 1.0).cgColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.0)
self.view.layer.addSublayer(gradientLayer)

//Image
let mainImage = UIImage(named:"WhiteLogoFront")
var mainImageView = UIImageView(image:mainImage)
self.view.addSubview(mainImageView)

Answer

Ram picture Ram · Feb 17, 2017

You can try it

let mainImage = UIImage(named:"WhiteLogoFront")
    var mainImageView = UIImageView(image:mainImage)
    mainImageView.contentMode = .ScaleAspectFit