Dan Matthews
Dan Matthews

Reputation: 1245

React native - animating the blurRadius of an Image

I have a "cover" image for the top of one of my views that i'd love to be able to blur out as you scroll it out of view as a cool effect.

My state contains a blurRadius property, which i am binding to the blurRadius={this.state.blurRadius} prop on my <Image> component.

I have a <ScrollView> and am monitoring when it's scrolled with onScroll, where i am calling setState({blurRadius: value}) - value being the distance that you've scrolled the view.

I've also set the scrollEventThrottle={30} prop on the scrollview so that i'm receiving the event regularly as the user scrolls.

The issue seems to be that the blurRadius updates but after a significant delay - and only to the maximum value. Am i missing something in order to make the image apply the new blurRadius with every call of setState?

Could it be that the image is just too large?

Upvotes: 0

Views: 2728

Answers (2)

jhm
jhm

Reputation: 4539

You should not use setState to set anything as a response to onScroll, as this leads to poor performance. The reason is that the whole view will rerender for every call to setState, which leads to "view thrashing".

Instead, you should use the Animated API, as this 'declares' the animation to the native UI thread, thus avoiding rerenders.

Brent Vatne (from the Expo team) gives a great explanation of Animated as well as a concrete example of animations as a response to onScroll events in ScrollView here

Hope it helps someone :-)

Upvotes: 2

rclai
rclai

Reputation: 1890

You can try using setNativeProps instead of setState to see if the performance improves. You just need to give your Image a ref.

this.refs.myImage.setNativeProps({ blurRadius: myValue });

Reducing the image size would also help as it would not need to blur as many pixels.

Upvotes: 0

Related Questions