Home > Blockchain >  How to give different colours to inner and outer border in SwiftUI?
How to give different colours to inner and outer border in SwiftUI?

Time:01-07

I am trying to create a border like the one shown in the image. As can be seen, the outer and inner parts of the border have different colours. I tried to create this using .stroke and overlaying another on top of it but that did not work:

  .overlay( 
            RoundedRectangle(cornerRadius: 4)
                                        .stroke(.gray.opacity(0.5), lineWidth: 4)
                              
                                  .overlay (
                                    RoundedRectangle(cornerRadius: 8)
                                        .stroke(.black.opacity(1), lineWidth: 1))
                                    
                                )

How can I achieve this affect in SwiftUI?

image of the border I am trying to replicate

CodePudding user response:

Agreed with Nathan, and you'll need to adjust your corner radius as well to so they match up as one will be on the outer perimeter of the other. That said, you can add the behavior in this code snippet where I moved the black outer line out one level:

    import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("Hello, world!")
        }
        .padding()
        .overlay(
            RoundedRectangle(cornerRadius: 10)
                .stroke(.gray.opacity(0.5), lineWidth: 20)
        )
        .padding()
        .overlay (
            RoundedRectangle(cornerRadius: 30)
                .stroke(.black.opacity(1), lineWidth: 10))

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

That said, you can also look at this article by Anmol Maheshwari n the SwiftUI forum on Medium a couple of years ago:

https://medium.com/swiftui-forum/rounded-corners-with-gradient-and-border-5858590fc9d3

  • Related