Code Changes:
1. ZStack Alignment
ZStack(alignment: Alignment(horizontal: .trailing, vertical: .bottom)) {
2. Crop in the center
In NetworkImage
, center crop (code provided) in the image extension.
Thanks to @vacawama
How to center crop an image in SwiftUI
Complete Code:
struct ContentView: View {
var body: some View {
ZStack(alignment: Alignment(horizontal: .trailing, vertical: .bottom)) {
NetworkImage(url: URL(string: "https://unsplash.com/photos/KZv3Rb_OIXI/download?force=true"))
VStack(alignment: .trailing, spacing: 5) {
Spacer()
Text("this is my quite long title here")
.font(.title)
.bold()
.foregroundColor(.white)
.lineLimit(nil)
.multilineTextAlignment(.trailing)
Text("subtitle this is my long long subtitle to create multiply lines")
.font(.caption)
.foregroundColor(.white)
.lineLimit(nil)
.multilineTextAlignment(.trailing)
}
.padding()
}
}
}
//Center Crop
extension Image {
func centerCropped() -> some View {
GeometryReader { geo in
self
.resizable()
.scaledToFill()
.frame(width: geo.size.width, height: geo.size.height)
.clipped()
}
}
}
struct NetworkImage: View {
let url: URL?
var body: some View {
if let url = url, let imageData = try? Data(contentsOf: url), let uiImage = UIImage(data: imageData) {
Image(uiImage: uiImage)
.centerCropped()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…