TruMan1
TruMan1

Reputation: 36178

How to make a border from a view in SwiftUI?

I'd like to make a 2px border from a view, but the border only accepts a ShapeStyle. I'm trying to do something like:

let specialRadialGradient = GeometryReader { geometry in
    RadialGradient(
        gradient: Gradient(
            stops: [
                .init(color: Color("gradient1").opacity(0.5), location: 0),
                .init(color: Color("gradient2").opacity(0.5), location: 1)
            ]
        ),
        center: .init(x: 0.1432, y: 0.7254
        startRadius: .zero,
        endRadius: geometry.size.width * 0.75
    )
    .background(Color.brandPrimary)
}

Text("Abc")
  .frame(maxWidth: .infinity)
  .padding()
  .border(specialRadialGradient, 2)

However, since the specialRadialGradient view is wrapped in a GeometryReader to handle the radial gradient properly in all ratio sizes, it doesn't compile. How can I cut out a 2px border out of specialRadialGradient and apply it to the background of the text?

Upvotes: 2

Views: 494

Answers (1)

Asperi
Asperi

Reputation: 258491

Instead of border it can be done with composition of background and blending mode.

Here is a demo of possible approach. Tested with Xcode 14 / iOS 16

*(gradient colours just replicated for demo) demo

let borderWidth = 2.0
Text("Abc")
    .frame(maxWidth: .infinity)
    .padding()
    .background(
        specialRadialGradient
            .overlay(Rectangle().padding(borderWidth)    // << here !!
                .blendMode(.destinationOut))
            .compositingGroup()   // << important !!
    )

Test code on GitHub

Upvotes: 1

Related Questions