【问题标题】:Set view background from image view从图像视图设置视图背景
【发布时间】:2020-04-09 03:34:37
【问题描述】:

我正在尝试将UIImageView 中放置的任何图像与视图控制器视图的背景图像相匹配。因此,当用户在下面的示例中调用func call 时,图像视图choosenBack 中的任何图像都会显示为视图控制器的背景。如果图像视图中没有放置图像,则视图背景图像应为nil

choosenBack = UIImageView()

func call(){
    self.view.backgroundColor == UIColor(patternImage: UIImage(choosenBack)!)
}

【问题讨论】:

  • 你遇到了什么问题?

标签: swift uiview uiviewcontroller uiimageview uiimage


【解决方案1】:

仅当您确实希望重复图像以填充背景时,使用backgroundColor 属性才有效。在这种情况下,你可以简单地做类似的事情

func call() {
    if let image = choosenBack.image {
        self.view.backgroundColor = UIColor(patternImage: image)
    } else {
        self.view.backgroundColor = .white // Or w/e your default background is
    }
}

如果您希望背景图像重复,则需要使用专用的背景图像视图。

let background = UIImageView()

override func viewDidLoad() {
    super.viewDidLoad()

    background.contentMode = .scaleAspectFit // Or w/e your desired content mode is

    view.insertSubview(background, at: 0)
    background.translatesAutoresizingMaskIntoConstraints = false
    background.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    background.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    background.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    background.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

    ...
}

func call() {
    self.background.image = choosenBack.image
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-28
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多