如何将渐变前景色文本移动到 SwiftUI 中的视图中心?

How to move the gradient-foreground-color text to the center of the view in SwiftUI?

我使用 Gradient.mask(_:) 修饰符来在 SwiftUI 中实现具有渐变前景色的 Text。但文本始终位于视图的最前面。我怎样才能把它放在视图的中心?

这是我的实现:

import SwiftUI

struct GradientText: View {
    var body: some View {
        LinearGradient(gradient: Gradient(colors: [.blue, .red, .orange]), 
                       startPoint: .leading, endPoint: .trailing)
            .mask(Text("Hello, world!")
                .font(.system(size: 40, weight: .bold, design: .rounded)))
            .padding()
    }
}

它看起来如何:

问题是 LinearGradient 填满了给定的所有 space。如果您删除 mask,您将看到它有多大。您希望它只是文本的大小。

我确信有更好的方法来处理这个问题,但这是我想出的方法。从文本开始,我们可以将 LinearGradient 用作 overlay,这将与文本的大小完全匹配。

struct GradientText: View {
    let text = Text("Hello World")
        .font(.system(size: 40, weight: .bold, design: .rounded))
    
    var body: some View {
        text
        .foregroundColor(.clear)
        .overlay(
            LinearGradient(gradient: Gradient(colors: [.blue, .red, .orange]),
                startPoint: .leading, endPoint: .trailing)
            .mask(text))
    }
}

进一步扩展这个想法,您可以让 GradientTexttextgradient 作为输入,这样您就可以轻松地重复执行此操作:

struct GradientText: View {
    let text: Text
    let gradient: LinearGradient
    
    init(text: Text, gradient: LinearGradient? = nil) {
        self.text = text
        self.gradient = gradient ?? LinearGradient(gradient: Gradient(colors: [.blue, .red, .orange]), startPoint: .leading, endPoint: .trailing)
    }
    
    var body: some View {
        text
        .foregroundColor(.clear)
        .overlay(
            gradient
            .mask(text))
    }
}

struct ContentView: View {
    var body: some View {
        VStack {
            GradientText(text: Text("Hello World")
                .font(.system(size: 40, weight: .bold, design: .rounded)))
            GradientText(text: Text("Goodnight World"), gradient: LinearGradient(gradient: Gradient(colors: [.green, .yellow, .orange]), startPoint: .leading, endPoint: .trailing))
        }
    }
}