Moj*_*ini 22
使用ZStack但不要使用UIScreen:
var body: some View {
ZStack {
Image("BG")
.resizable()
.scaledToFill()
.edgesIgnoringSafeArea(.all)
Text("Hello world")
}
}
Run Code Online (Sandbox Code Playgroud)
UIScreen如果您支持多屏应用、可调整大小的窗口、多窗口应用等,使用将导致您的应用出现不良行为。
更新
使用 iOS 15 Xcode 13.2
public extension View {
func fullBackground(imageName: String) -> some View {
return background(
Image(imageName)
.resizable()
.scaledToFill()
.edgesIgnoringSafeArea(.all)
)
}
}
Run Code Online (Sandbox Code Playgroud)
使用
YourView
.fullBackground(imageName: "imageName")
Run Code Online (Sandbox Code Playgroud)
结束更新
旧答案
我更喜欢@ViewBuilder
用法:
BackgroundView(imageName: "image name") {
Text("Hello")
}
Run Code Online (Sandbox Code Playgroud)
@ViewBuilder
public struct BackgroundView <Content : View> : View {
public var content : Content
public var imageName: String
public var opacity: Double
public init(imageName: String, opacity: Double=1,@ViewBuilder content: () -> Content) {
self.content = content()
self.imageName = imageName
self.opacity = opacity
}
public var body: some View {
GeometryReader { geo in
ZStack {
Image(imageName)
.resizable()
.scaledToFill()
.edgesIgnoringSafeArea(.all)
.frame(width: geo.size.width, height: geo.size.height, alignment: .center)
.opacity(opacity)
content
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
尝试这个:
var body: some View {
ZStack {
Text("Hello")
}
.background(
Image("Background")
.resizable()
.edgesIgnoringSafeArea(.all)
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
)
}
Run Code Online (Sandbox Code Playgroud)
如果您只想使用全屏宽度和高度,并且不关心图像的长宽比,则可以使用 UIScreen 尺寸的几何读取器。
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
Run Code Online (Sandbox Code Playgroud)
这行代码将把图像设置为设备的最大尺寸。根据您的家长视图和设备,您可能需要使用:
.edgesIgnoringSafeArea(.all)
Run Code Online (Sandbox Code Playgroud)
这将忽略 iPhone X 及更高版本设备上的安全区域。
| 归档时间: |
|
| 查看次数: |
9264 次 |
| 最近记录: |