Gradient as foreground color of Text in SwiftUI

后端 未结 6 1062
终归单人心
终归单人心 2021-02-08 12:55

Is there any way of using a gradient as foregroundColor of Text in SwiftUI?

Thanks for the answers in advance!

6条回答
  •  离开以前
    2021-02-08 13:15

    You can assign any gradient or other type of view as a self-size mask like:

    Text("Gradient is on FIRE !!!")
        .selfSizeMask(
            LinearGradient(
                gradient: Gradient(colors: [.red, .yellow]),
                startPoint: .bottom,
                endPoint: .top)
        )
    

    with this simple tiny extension:

    extension View {
        func selfSizeMask(_ mask: T) -> some View {
            ZStack {
                self.opacity(0)
                mask.mask(self)
            }.fixedSize()
        }
    }
    

    Demo


提交回复
热议问题