Home iOS Development ios – SwiftUI Ripple Effect Animation

ios – SwiftUI Ripple Effect Animation

0

[ad_1]

I’m working on creating a ripple effect in SwiftUI similar to the one here.

Here is what I have so far:

import SwiftUI

// MARK: - Ripple

struct Ripple: ViewModifier {
    // MARK: Lifecycle

    init(rippleColor: Color) {
        self.rippleColor = rippleColor
    }

    // MARK: Internal

    let rippleColor: Color

    func body(content: Content) -> some View {
        ZStack {
            content

            if let location = touchPoint {
                Circle()
                    .fill(rippleColor)
                    .frame(width: 16.0, height: 16.0)
                    .position(location)
                    .clipped()
                    .opacity(opacity)
            }
        }
        .fixedSize()
        .gesture(
            DragGesture(minimumDistance: 0.0)
                .onChanged { gesture in
                    guard touchPoint != gesture.startLocation else {
                        return
                    }

                    timer?.invalidate()

                    opacity = 1.0
                    touchPoint = gesture.startLocation
                }
                .onEnded { _ in
                    timer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false) { _ in
                        withAnimation {
                            opacity = 0.0
                        }
                    }
                }
        )
    }

    // MARK: Private

    @State private var opacity: CGFloat = 0.0
    @State private var touchPoint: CGPoint?
    @State private var timer: Timer?
}

extension View {
    func rippleEffect(rippleColor: Color = .accentColor.opacity(0.5)) -> some View {
        modifier(Ripple(rippleColor: rippleColor))
    }
}

The next step is to do the scaling animation, but I’m having trouble figuring out how. I’ve tried applying scale effects and transitions with the scale modifier, but nothing seems to work correctly.

Can someone assist me in achieving the ripple effect I’m looking for?

Additionally, if something like this already exists, I’d be happy to just use it, but I haven’t been able to find anything.

Thanks,

RPK

[ad_2]