Search code examples
iosanimationswiftuiuikitborder

Snake like gradient border animation in iOS


I am trying to create snake like view border animation with gradient colour, see the image below.

I have tried this UIKit solution, but CAGradientLayer with CAKeyframeAnimation is not working. It is coming as background view not as a border.

Also I tried with SwiftUI, but the gradient animation is breaking for some dynamic height and width. Below is the SwiftUI code I have used:

struct GradientBorderAnimationView: View {
  @State var rotation:CGFloat = 0.0

  @State var width: CGFloat = 330
  @State var height: CGFloat = 100

  var body: some View {
    ZStack{
        RoundedRectangle(cornerRadius: 20, style: .continuous)
            .frame(width: width*2, height: height*2)
            .foregroundStyle(LinearGradient(gradient: Gradient(colors: [.white, .white, .blue]),
                                            startPoint: .top,
                                            endPoint: .bottom))
            .rotationEffect(.degrees(rotation))
            .mask {
                RoundedRectangle(cornerRadius: 20, style: .continuous)
                    .stroke(lineWidth: 3)
                    .frame(width: width, height: height)
            }
    }
    .ignoresSafeArea()
    .onAppear{
        withAnimation(.linear(duration: 4).repeatForever(autoreverses: false)){
            rotation = 360
        }
    }
  }
}

Output:

enter image description here

Expected Output:

enter image description here

Can anyone tell me what is the issue in the above code or if anyone has any better solution, that also works. I am okay with SwiftUI and UIKit anything.


Solution

  • You should use AngularGradient instead, like:

    AngularGradient(colors: [.white, .white, .blue], center: .center)
    

    So combined with your original code, it would be like:

    Demo

    Note that I've removed the manual size but you can play with properties to match your specific needs.