ios 如何快速将背景图像缩放到屏幕大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27153181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you make a background image scale to screen size in swift?
提问by GuiGui23
I'm trying to make a UIView image for my background in swift using pattern image. The code I have works well except for the fact that I want the image to take the whole screen. My code looks like this: self.view.backgroundColor = UIColor(patternImage: UIImage(named: "backgroundImage")!)
我正在尝试使用图案图像快速为我的背景制作 UIView 图像。我的代码运行良好,除了我希望图像占据整个屏幕的事实。我的代码如下所示:self.view.backgroundColor = UIColor(patternImage: UIImage(named: "backgroundImage")!)
Does anyone know how to make the background an image that will take up the whole screen, and would scale when appearing on different iPhone screen sizes?
有谁知道如何使背景成为占据整个屏幕的图像,并且在出现在不同的 iPhone 屏幕尺寸上时会缩放?
回答by Ahmad Fayyas
Note That:
注意:
I posted this answer from my old account (which is deprecated for me and I can't access it anymore), this is my improved answer.
我从我的旧帐户发布了这个答案(对我来说已被弃用,我无法再访问它),这是我改进的答案。
You can do it programmatically instead of creating an IBOutlet in each view. just create a UIView extension(File -> New -> File -> Swift File -> name it whatever you want) and add:
您可以通过编程方式来完成,而不是在每个视图中创建一个 IBOutlet。只需创建一个 UIView扩展(文件 -> 新建 -> 文件 -> Swift 文件 -> 随意命名)并添加:
extension UIView {
func addBackground() {
// screen width and height:
let width = UIScreen.mainScreen().bounds.size.width
let height = UIScreen.mainScreen().bounds.size.height
let imageViewBackground = UIImageView(frame: CGRectMake(0, 0, width, height))
imageViewBackground.image = UIImage(named: "YOUR IMAGE NAME GOES HERE")
// you can change the content mode:
imageViewBackground.contentMode = UIViewContentMode.ScaleAspectFill
self.addSubview(imageViewBackground)
self.sendSubviewToBack(imageViewBackground)
}}
Now, you can use this method with your views, for example:
现在,您可以在视图中使用此方法,例如:
override func viewDidLoad() {
super.viewDidLoad()
self.view.addBackground()
}
回答by Leo Dabus
Just add your UIImageView positioned centered and with all edges snapping to the edges. Leave it there and click on the right bottom corner as shown below and now go ahead and add 4 constrains to Top, Bottom, Left and Right Edges.
只需添加您的 UIImageView 定位居中并且所有边缘都对齐边缘。将其留在那里并单击右下角,如下所示,现在继续向顶部、底部、左侧和右侧边缘添加 4 个约束。
Now just select your image view and using the IB inspector select how you would like your image: fill or fit as you can see as follow:
现在只需选择您的图像视图并使用 IB 检查器选择您希望图像的方式:填充或适合,如下所示:
回答by Ahmad F
This is the updated answer of my previous one.
这是我上一个的更新答案。
As the same approach of my previous answer, You can create an extension of UIView and add addBackground()
method to it, as follows:
与我之前的答案相同,您可以创建 UIView 的扩展addBackground()
并向其添加方法,如下所示:
Remember: if you are adding it in a new .swift file, remember to add import UIKit
请记住:如果您要将其添加到新的 .swift 文件中,请记住添加 import UIKit
extension UIView {
func addBackground(imageName: String = "YOUR DEFAULT IMAGE NAME", contentMode: UIView.ContentMode = .scaleToFill) {
// setup the UIImageView
let backgroundImageView = UIImageView(frame: UIScreen.main.bounds)
backgroundImageView.image = UIImage(named: imageName)
backgroundImageView.contentMode = contentMode
backgroundImageView.translatesAutoresizingMaskIntoConstraints = false
addSubview(backgroundImageView)
sendSubviewToBack(backgroundImageView)
// adding NSLayoutConstraints
let leadingConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0.0)
let trailingConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0.0)
let topConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0)
let bottomConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0.0)
NSLayoutConstraint.activate([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])
}
}
Note that the updates for this answer are:
请注意,此答案的更新是:
- Swift 4 code
- Adding -programatically- NSLayoutConstraints: that's because when applying what's mentioned in my previous answer, it works fine for the current device orientation, but notwhen the application does support both portrait/landscape modes, if the device orientation has been changed, the background imageView size will be the same (same size) and not adapts the new width/height of the device screen, so adding constraints should solve this issue.
- Adding default parameters: for more flexibility, you might -sometimes- want to change the default image or even the context mode for you background:
- 斯威夫特 4 代码
- 添加-programatically- NSLayoutConstraints:那是因为采用什么在我以前的答复时提到,它工作正常,当前设备的方向,但不是当应用程序不支持纵向/横向模式下,如果设备的方向已经改变,后台的ImageView大小将相同(相同大小)并且不适应设备屏幕的新宽度/高度,因此添加约束应该可以解决这个问题。
- 添加默认参数:为了获得更大的灵活性,您有时可能希望更改默认图像甚至背景的上下文模式:
Usage:
用法:
Assuming that you want to call it in viewDidLoad()
:
假设你想调用它viewDidLoad()
:
override func viewDidLoad() {
//...
// you can call 4 versions of addBackground() method
// 1- this will add it with the default imageName and default contextMode
view.addBackground()
// 2- this will add it with the edited imageName and default contextMode
view.addBackground(imageName: "NEW IMAGE NAME")
// 3- this will add it with the default imageName and edited contextMode
view.addBackground(contentMode: .scaleAspectFit)
// 4- this will add it with the default imageName and edited contextMode
view.addBackground(imageName: "NEW IMAGE NAME", contextMode: .scaleAspectFit)
}
回答by MacInnis
Here are your options for scaling!
这是您的缩放选项!
For the .contentMode property:
对于 .contentMode 属性:
ScaleToFill This will scale the image inside the image view to fill the entire boundaries of the image view.
ScaleToFill 这将缩放图像视图内的图像以填充图像视图的整个边界。
ScaleAspectFit This will make sure the image inside the image view will have the right aspect ratio and fit inside the image view's boundaries.
ScaleAspectFit 这将确保图像视图内的图像具有正确的纵横比并适合图像视图的边界。
ScaleAspectFill This will make sure the image inside the image view will have the right aspect ratio and fill the entire boundaries of the image view. For this value to work properly, make sure that you have set the clipsToBounds property of the imageview to true.
ScaleAspectFill 这将确保图像视图内的图像具有正确的纵横比并填充图像视图的整个边界。为了使该值正常工作,请确保已将 imageview 的 clipsToBounds 属性设置为 true。
class SecondViewController : UIViewController {
let backgroundImage = UIImage(named: "centralPark")
var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.thirdChoiceField.delegate = self
self.datePicker.minimumDate = NSDate()
imageView = UIImageView(frame: view.bounds)
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
imageView.image = backgroundImage
imageView.center = view.center
view.addSubview(imageView)
self.view.sendSubviewToBack(imageView)
回答by ochhii
Ahmad Fayyas Solution in Swift 3.0:
Swift 3.0 中的 Ahmad Fayyas 解决方案:
func addBackground() {
let width = UIScreen.main.bounds.size.width
let height = UIScreen.main.bounds.size.height
let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width: width, height: height))
imageViewBackground.image = UIImage(named: "YOUR IMAGE NAME GOES HERE")
// you can change the content mode:
imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill
self.view.addSubview(imageViewBackground)
self.view.sendSubview(toBack: imageViewBackground)
}
回答by Stephen Johnson
This uses PureLayout. You could just use AutoLayout with a few more lines.
这使用PureLayout。您可以使用多几行的 AutoLayout。
UIImageView* imgView = UIImageView(image: myUIImage)
imgView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(imgView)
self.view.addConstraints(imgView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(0,0,0,0))
回答by Pablo
I used constraints to make the image "autoLayout". I made a view to show an activity indicator (with full background image), while the view on segue is loading. The code is as follows.
我使用约束使图像“自动布局”。我做了一个视图来显示一个活动指示器(带有完整的背景图像),而 segue 上的视图正在加载。代码如下。
var containerView: UIView = UIView()
var actionIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
private func showActivityIndicator() {
///first I set the containerView and the background image
containerView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(containerView)
adjustConstFullSize(containerView, parentView: self.view)
let backImage = UIImageView(image: UIImage(named: "AppBackImage"))
backImage.contentMode = UIViewContentMode.ScaleAspectFill
backImage.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(backImage)
adjustConstFullSize(backImage, parentView: containerView)
////setting the spinner (activity indicator)
actionIndicator.frame = CGRectMake(0.0, 0.0, 40.0, 40.0)
actionIndicator.center = CGPointMake(containerView.bounds.size.width / 2, containerView.bounds.size.height / 2)
actionIndicator.hidesWhenStopped = true
actionIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
containerView.insertSubview(actionIndicator, aboveSubview: backImage)
///throw the container to the main view
view.addSubview(containerView)
actionIndicator.startAnimating()
}
This is the code for the "adjustConstFullSize" function.
这是“adjustConstFullSize”函数的代码。
func adjustConstFullSize(adjustedView: UIView!, parentView: UIView!) {
let topConstraint = NSLayoutConstraint(item: adjustedView,
attribute: .Top,
relatedBy: .Equal,
toItem: parentView,
attribute: .Top,
multiplier: 1.0,
constant: 0.0)
let leftConstraint = NSLayoutConstraint(item: adjustedView,
attribute: .Leading,
relatedBy: .Equal,
toItem: parentView,
attribute: .Leading,
multiplier: 1.0,
constant: 0.0)
let rightConstraint = NSLayoutConstraint(item: adjustedView,
attribute: .Trailing,
relatedBy: .Equal,
toItem: parentView,
attribute: .Trailing,
multiplier: 1.0,
constant: 0.0)
let bottomConstraint = NSLayoutConstraint(item: adjustedView,
attribute: .Bottom,
relatedBy: .Equal,
toItem: parentView,
attribute: .Bottom,
multiplier: 1.0,
constant: 0.0)
parentView.addConstraints([topConstraint, leftConstraint, rightConstraint, bottomConstraint])
}
In the function shown above, I "tied" the containerView constraints to the main view constraints, making the view "full size". I did the same for the UIImageView and also set the contentMode to AspectFill - this is crucial, because we want the image to fill the content without stretching.
在上面显示的函数中,我将 containerView 约束“绑定”到主视图约束,使视图“全尺寸”。我对 UIImageView 做了同样的事情,并将 contentMode 设置为 AspectFill - 这很重要,因为我们希望图像在不拉伸的情况下填充内容。
To remove the view, after the lazy loading, just use the code below.
要删除视图,在延迟加载后,只需使用下面的代码。
private func hideActivityIndicator() {
actionIndicator.stopAnimating()
containerView.removeFromSuperview()
}
回答by Robert William Clancy
`
`
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
_imgBackGround.frame = CGRectMake(0, 0, screenWidth, screenHeight);`
回答by wottle
For this, I think you'll need to create a UIImageView that is pinned to the parent views top / bottom / left / right. This will make the UIImageView always the match the size of the display. Just make sure you set the content mode on the imageview to be AspectFit
为此,我认为您需要创建一个 UIImageView 固定到父视图的顶部/底部/左侧/右侧。这将使 UIImageView 始终匹配显示的大小。只需确保将 imageview 上的内容模式设置为 AspectFit
var newImgThumb : UIImageView
newImgThumb = UIImageView(view.bounds)
newImgThumb.contentMode = .ScaleAspectFit
view.addSubview(newImgThumb)
//Don't forget this line
newImgThumb.setTranslatesAutoresizingMaskIntoConstraints(false)
NSDictionary *views =NSDictionaryOfVariableBindings(newImgThumb);
// imageview fills the width of its superview
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[newImgThumb]|" options:0 metrics:metrics views:views]];
// imageview fills the height of its superview
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[newImgThumb]|" options:0 metrics:metrics views:views]];