Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - how to pulsate image opacity?

I have an Image in SwiftUI that I would like to "pulsate" (come & go every second or so) forever.

I tried a number of things but I can't seem to get the effect I want. One of the things I tried is the code below (which seems to do nothing! :) ).

Image(systemName: "dot.radiowaves.left.and.right" )
.foregroundColor(.blue)
.transition(.opacity)
.animation(Animation.easeInOut(duration: 1)
    .repeatForever(autoreverses: true))

Any ideas?

like image 384
Gerard Avatar asked Oct 28 '25 10:10

Gerard


2 Answers

Here is an approach. Tested with Xcode 11.4 / iOS 13.4

demo

struct DemoImagePulsate: View {
    @State private var value = 1.0
    var body: some View {
        Image(systemName: "dot.radiowaves.left.and.right" )
            .foregroundColor(.blue)
            .opacity(value)
            .animation(Animation.easeInOut(duration: 1).repeatForever(autoreverses: true))
        .onAppear { self.value = 0.3 }
    }
}
like image 129
Asperi Avatar answered Oct 30 '25 08:10

Asperi


iOS 16 Update

The accepted answer is great, but since iOS 15 things have changed slightly, you'll get a deprecation warning with Asperi's code, the updated code is:

// Instead of the `animation` modifier, just have this in onAppear: 
.onAppear {
    withAnimation(.easeInOut(duration: 1).repeatForever(autoreverses: true)) {
        value = 0.3
    }
}
like image 34
Nikolay Suvandzhiev Avatar answered Oct 30 '25 07:10

Nikolay Suvandzhiev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!