article

Wednesday, September 15, 2021

SwiftUI Text Stroke Border

SwiftUI Text Stroke Border

In this tutorial I will show how to create a glowing border around SwiftUI text

ContentView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//
 
import SwiftUI
 
struct ContentView: View {
     
    var body: some View {
        ZStack {
            Image("digitalart")
                .scaledToFill()
                .ignoresSafeArea()
             
            Text("Hello Cairocoders")
                .font(.largeTitle)
                .glowBorder(color: .pink, lineWidth: 6)
             
            Text("Text glowing border")
                .font(.largeTitle)
                .glowBorder(color: .orange, lineWidth: 10)
                .padding(.top, 190)
        }
    }
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView() 
    }
}
 
 
struct GlowBorder: ViewModifier {
    var color: Color
    var lineWidth: Int
     
    func body(content: Content) -> some View {
        applyShadow(content: AnyView(content), lineWidth: lineWidth)
    }
     
    func applyShadow(content: AnyView, lineWidth: Int) -> AnyView {
        if lineWidth == 0 {
            return content
        } else {
            return applyShadow(content: AnyView(content.shadow(color: color, radius: 1)), lineWidth: lineWidth - 1)
        }
    }
}
 
extension View {
    func glowBorder(color: Color, lineWidth: Int) -> some View {
        self.modifier(GlowBorder(color: color, lineWidth: lineWidth))
    }
}

Related Post