Swift如何在这张图片中制作背景?

时间:2017-07-19 18:29:47

标签: ios swift

我正在尝试创建此图像中的背景enter image description here

所以我创造了一个图像 enter image description here

这是我的代码

let background_image: UIImageView = {
    let view = UIImageView()
    view.image = #imageLiteral(resourceName: "backg")
    view.contentMode = .scaleToFill
    return view
}()

background_image.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
background_image.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
background_image.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
background_image.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true

但问题是因为屏幕高度大于宽度,使图像看起来像高度一样扩大,就像这样 enter image description here

如何使图像仅填充屏幕的宽度而不是高度?

2 个答案:

答案 0 :(得分:0)

您是否尝试过使用colorWithPatternImage方法(见下文)?

UIImage *patternImage = [UIImage imageNamed:@"bluewhite.png"];
self.view.backgroundColor = [UIColor colorWithPatternImage:patternImage];

在Swift 3中,它看起来像这样:

var patternImage = UIImage(named:"bluewhite.png")
self.view.backgroundColor = UIColor(patternImage: patternImage!)

但是对于一个数组或一组图像,您可以在主视图后面使用Collection View并配置每个集合视图项的背景,如下所示:

self.collectionView.backgroundColor = UIColor(colorWithPatternImage:patternImage!)

请参阅此question讨论类似问题。

答案 1 :(得分:0)

view.contentMode = .scaleToFill

应该是

view.contentMode = .scaleAspectFill
相关问题