如何在 Swift 3 中使图像居中和纵横比?

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

我在 Swift 3 中有一个项目,我在视图上使用渐变。我在视图上放了一张图片,但它在渐变层下面,所以我打算以编程方式绘制图片,而不是使用故事板。我似乎无法弄清楚如何使图像居中并在视图边界内进行纵横比调整。

我有什么...

//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)

你可以试试

let mainImage = UIImage(named:"WhiteLogoFront")
    var mainImageView = UIImageView(image:mainImage)
    mainImageView.contentMode = .ScaleAspectFit
 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)
    mainImageView.center = self.view.cente
    mainImageView.contentMode = .ScaleAspectFit
    self.view.addSubview(mainImageView)

试试这个