xcode iOS 保持 UIImageView 的纵横比但填充宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29598301/
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
iOS keep aspect ratio of UIImageView but fill width
提问by Jhorra
This is my first app from scratch under iOS 8 and XCode 6, so these spacing issues have been killing me. In the below you can see I have an UIImageView that I want to be a square, but I want it to stretch across the width of the screen as well.It has a width and height value so when the app runs the screen is wider so it ends up a tiny box in the top left corner. I've tried messing around with the constraints in every way I could think of, but when I constrain it the image blows up to full size and covers everything going off the screen. How do I get it to stretch and keep the 1 to 1 aspect ratio?
这是我在 iOS 8 和 XCode 6 下从头开始的第一个应用程序,所以这些间距问题一直困扰着我。在下面你可以看到我有一个 UIImageView,我想成为一个正方形,但我希望它也能横跨屏幕的宽度。它有一个宽度和高度值,所以当应用程序运行时,屏幕更宽它最终会在左上角出现一个小盒子。我尝试过以我能想到的各种方式来处理约束,但是当我约束它时,图像会放大到全尺寸并覆盖屏幕外的所有内容。如何让它拉伸并保持 1 比 1 的纵横比?
EDITOk, I was wrong. It's not the UIImageView that's not adjusting, it's the entire view.
编辑好吧,我错了。不是 UIImageView 没有调整,而是整个视图。
采纳答案by Kristaps Vītols
Constrain both sides and top to superview. You can also say that, for example, width/height can be >= 320, which sometimes helps. But remember, it will only work in portrait, when you turn the UI to landscape, the image can never stay square while filling the width and being fully onscreen at the same time.
将两侧和顶部限制为超级视图。您也可以说,例如,宽度/高度可以 >= 320,这有时会有所帮助。但请记住,它仅适用于纵向,当您将 UI 变为横向时,图像在填充宽度和完全显示在屏幕上的同时永远不会保持方形。
EDIT:the image should not try to stretch beyond screen bounds (in portrait) as long as you do not tell it that it should be "this far from the bottom"
编辑:图像不应试图超出屏幕边界(纵向),只要您不告诉它应该“离底部这么远”
EDIT - 2:Set the background view constraints to superview. all 4.
编辑 - 2:将背景视图约束设置为超级视图。所有 4。
回答by Enrico Susatyo
Use the image view content mode:
使用图像查看内容模式:
[self.imageView setContentMode:UIViewContentModeScaleAspectFill];
It seems like you also want the width of the frame to fill the screen. Use these constraints:
似乎您还希望框架的宽度填满屏幕。使用这些约束:
- Distance to top, left, and right to 0.
- Height equals to width constraint.
- Image ratio 1:1 constraint.
- 到顶部、左侧和右侧的距离为 0。
- 高度等于宽度约束。
- 图像比例 1:1 约束。
Then the image view should be resized appropriately.
然后应该适当地调整图像视图的大小。
回答by Cody Weaver
I would set the frame programmatically and not use constraints at all. To do that
我会以编程方式设置框架,根本不使用约束。要做到这一点
- Link the ImageView to an outlet in its View Controller
Set the frame so the two values are equal
frame.size.width/frame.size.height
- 将 ImageView 链接到其视图控制器中的插座
设置框架使两个值相等
frame.size.width/frame.size.height