[英]Image full screen width in SwiftUI
I added an image to my body in a SwiftUI application and want to have that image cover the full width of the device, but not go over it. 我在SwiftUI应用程序中向我的身体添加了一个图像,并希望该图像能够覆盖设备的整个宽度,但不能覆盖整个图像。
In body
, I return the image object: 在
body
,我返回了图像对象:
var body: some View {
Image("page-under-construction")
}
and the image shows up, however, it's too big: 并且图像显示出来,但是,它太大了:
I tried setting the frame: that affects the highlighted boundaries, but the image does not resize. 我尝试设置框架:这会影响突出显示的边界,但图像不会调整大小。
In combination, I played around with .aspectRatio(contentMode:)
, which did not seem to have any effect on the layout. 结合起来,我玩了
.aspectRatio(contentMode:)
,它似乎对布局没有任何影响。
How can I have the image be effectively 100% of the screen width? 如何使图像有效地达到屏幕宽度的100%?
The reason .aspectRatio(contentMode:)
had no effect on the layout is because you did not make the image resizable with resizeable()
. .aspectRatio(contentMode:)
对布局没有影响的原因是,您没有使用resizeable()
使图像可调整resizeable()
。
Doing 在做
var body: some View {
Image("page-under-construction")
.resizable()
.aspectRatio(contentMode: .fill)
}
will cause the image to be the width of the screen, but the image's aspect ratio will not be maintained. 会导致图像成为屏幕的宽度,但不会保持图像的纵横比。 To maintain the aspect ratio, do
要保持长宽比,请执行
var body: some View {
Image("page-under-construction")
.resizable()
.aspectRatio(UIImage(named: "page-under-construction")!.size, contentMode: .fill)
}
This utilizes the .aspectRatio(aspectRatio: CGSize, contentMode: ContentMode)
version of the method your original question discussed with a dummy UIImage to access the Image's original aspect ratio. 这利用您的原始问题与虚拟UIImage讨论的方法的
.aspectRatio(aspectRatio: CGSize, contentMode: ContentMode)
版本来访问图像的原始纵横比。
Note: The explicitly unwrapped optional ( !
) should not be a problem unless you are unsure if the image name is a valid one from your Assets folder. 注意:除非您不确定图像名称是否是Assets文件夹中的有效名称,否则显式展开的可选(
!
)应该不会成为问题。 See this post for a comprehensive overview on Swift optionals. 请参阅本文以获取有关Swift可选对象的全面概述。
Did you try resizable modifier? 您是否尝试过调整大小的修饰符?
struct ImageView: View {
var body: some View {
Image("turtlerock")
.resizable()
.aspectRatio(contentMode: .fit)
}}
Note - There are 2 content modes: .fit and .fill 注意-有2种内容模式:.fit和.fill
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.