简体   繁体   English

斯威夫特如何使背景像这张图片?

[英]Swift how to make a background like in this image?

I'm trying to create a background like in this image 我正在尝试创建这张图片中的背景 在此处输入图片说明

So i have created an image 所以我创建了一张图片 在此处输入图片说明

And here is my code 这是我的代码

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

But the problem is because the screen height is bigger than the width,is makes image looks expanded in height,like this 但是问题是因为屏幕的高度大于宽度,是使图像看起来在高度上展开,像这样 在此处输入图片说明

How can i make image to only fill the width of the screen not the height? 如何使图像仅填充屏幕的宽度而不填充屏幕的高度?

Have you tried using the colorWithPatternImage method (see below)? 您是否尝试过使用colorWithPatternImage方法(请参见下文)?

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

In Swift 3, it looks like this: 在Swift 3中,它看起来像这样:

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

But for an array or a group of images you can use a Collection View behind your main view and configure the background of each collection view item like this: 但是对于阵列或一组图像,您可以在主视图后面使用“收藏夹视图”,并按如下方式配置每个收藏夹视图项的背景:

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

See this question which discusses a similar issue. 看到这个问题 ,其中讨论了类似的问题。

view.contentMode = .scaleToFill

应该

view.contentMode = .scaleAspectFill

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

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