如何在 SwiftUI 中制作屏幕高度一半的图像?

Tru*_*an1 3 ios swiftui

我想让图像在屏幕上居中,但使其高度为屏幕高度的一半?这怎么可能?

use*_*ser 5

像这样,如果你有关于代码的问题请询问,我认为这很容易理解。

import SwiftUI

struct ContentView: View {
    var body: some View {

        Image(systemName: "person")
            .resizable()
            .frame(width: UIScreen.main.bounds.height/2, height: UIScreen.main.bounds.height/2)
            .aspectRatio(contentMode: .fit)
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:用于支持方向更改:

import SwiftUI

struct ContentView: View {

@State var sizeOfImage: CGFloat = UIScreen.main.bounds.height/2

var body: some View {

    Image(systemName: "person")
        .resizable()
        .frame(width: sizeOfImage, height: sizeOfImage)
        .aspectRatio(contentMode: .fit)
        .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
            sizeOfImage = UIScreen.main.bounds.height/2  }



    }
}
Run Code Online (Sandbox Code Playgroud)