Skip to content

Instantly share code, notes, and snippets.

@mahmudahsan
Created February 27, 2020 04:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahmudahsan/15a6ad80cd024852cf7366547928fc39 to your computer and use it in GitHub Desktop.
Save mahmudahsan/15a6ad80cd024852cf7366547928fc39 to your computer and use it in GitHub Desktop.
SwiftUI How to create a gradient text
import SwiftUI
extension Color {
static func hexStringToColor (hex:String, opacity: Double = 1.0) -> Color {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return Color.gray
}
var rgbValue:UInt64 = 0
Scanner(string: cString).scanHexInt64(&rgbValue)
return Color(
red: Double((rgbValue & 0xFF0000) >> 16) / 255.0,
green: Double((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: Double(rgbValue & 0x0000FF) / 255.0,
opacity: Double(opacity)
)
}
}
struct ContentView: View {
var body: some View {
VStack {
GradientText(title: "Good Morning")
.padding()
}
}
}
struct GradientText: View {
let title: String
let colors = Gradient(colors: [Color.hexStringToColor(hex: "#FF0000"),
Color.hexStringToColor(hex: "#40B482")])
var body: some View {
RadialGradient(gradient: colors,
center: .center,
startRadius: 0,
endRadius: 300)
.frame(height: 65)
.mask(Text("Good Morning")
.font(.system(size: 50))
)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment