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
//
//  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