简体   繁体   English

在 swift 中居中图像并添加背景

[英]Center image and add background in swift

So I have a screen that renders when the app is on the recents screen.所以我有一个屏幕,当应用程序在最近屏幕上时呈现。 But the issue is, it is on the top left and I can't align it to the center and also I couldn't set the background to white.但问题是,它位于左上角,我无法将其与中心对齐,也无法将背景设置为白色。 The white background has to cover the screen and this image should be in middle.白色背景必须覆盖屏幕,此图像应位于中间。 So far, I have managed to add the image.到目前为止,我已经设法添加了图像。 but no luck after that.但在那之后没有运气。 Any help would be appreciated.任何帮助,将不胜感激。

  override func applicationWillResignActive(_ application: UIApplication) {
   if let view = self.window.rootViewController?.view.subviews.first(where: {$0.tag == TAG_BLUR_VIEW}){
       view.removeFromSuperview()
       blurView = nil
   }
    if blurView == nil{
        blurView = UIImageView(image: UIImage(named: "splash.jpg"))
        blurView?.backgroundColor = UIColor .white
        blurView?.tag = TAG_BLUR_VIEW
    }
    
    self.window.rootViewController?.view.insertSubview(blurView!, at: 0)

  }

The simplest solution is to use a center position.最简单的解决方案是使用中心 position。

if blurView == nil {
   let centerPos = self.window?.rootViewController?.view.center ?? .zero
   blurView?.center = centerPos
   self.window?.rootViewController?.view.addSubview(blurView!)
}

So the final code snippet based on the provided code is like the following.
override func applicationWillResignActive(_ application: UIApplication) {
   if let view = self.window.rootViewController?.view.subviews.first(where: {$0.tag == TAG_BLUR_VIEW}){
       view.removeFromSuperview()
       blurView = nil
   }
    if blurView == nil{
        blurView = UIImageView(image: UIImage(named: "splash.jpg"))
        blurView?.backgroundColor = UIColor .white
        blurView?.tag = TAG_BLUR_VIEW

        let centerPos = self.window?.rootViewController?.view.center ?? .zero
        blurView?.center = centerPos
    }
    
    self.window.rootViewController?.view.insertSubview(blurView!, at: 0)

  }

You need to specify the constraints for your view.您需要为您的视图指定约束。

override func viewDidLoad() {
        blurView.translatesAutoresizingMaskIntoConstraints = false
        blurView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        // Add the other constraints such as topAnchor, leadingAnchor and trailingAnchor etc...
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM