简体   繁体   English

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

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

I used Gradient with a .mask(_:) modifier to implement Text with a gradient foreground color in SwiftUI.我用Gradient.mask(_:)修改来实现Text与SwiftUI渐变前景色。 But the text is always at the top-leading of the view.但文本始终处于视图的最前面。 How can I put it at the center of the view?我怎样才能把它放在视图的中心?

This is my implementation:这是我的实现:

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()
    }
}

And how does it look like:它是什么样子的:

在此处输入图片说明

The problem is that the LinearGradient is filling all of the space it is given.问题是LinearGradient填充了它给定的所有空间。 If you remove the mask , you will see how big it is.如果你取下mask ,你会看到它有多大。 You'd like it to be just the size of the text.您希望它只是文本的大小。

I'm sure there's a better way to handle this, but this is what I came up with.我确信有更好的方法来处理这个问题,但这就是我想出的。 By starting with the text, we are able to use the LinearGradient as an overlay which will exactly match the size of the text.通过从文本开始,我们可以将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))
    }
}

Extending this idea further, you could make GradientText take text and gradient as inputs so that you could easily do this repeatedly:进一步扩展这个想法,您可以让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))
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM