oblador / react-native-animatable

Standard set of easy to use animations and declarative transitions for React Native
MIT License
9.82k stars 701 forks source link

How to use imperative animations bundled with gestures? #271

Closed MehmetKaplan closed 4 years ago

MehmetKaplan commented 5 years ago

I am trying to generate a simple test application. The aim is to touch an image and move it on the screen.

The problem is, in the first time, the image animates just as expected. But when aimed to start second animation with the gesture, the image translation starts from its original coordinates. (The box jumps back to original coordinates and start second animation from that point.)

My question is, how to set the location (left / top values for example) to the final translated point so that consecutive animation starts from the point the previous translation left.

The expo snack for below code block is here.

The sample code:

import * as React from 'react';
import { Image, StyleSheet, ImageBackground } from 'react-native';

import * as Animatable from 'react-native-animatable';
import { PanGestureHandler, State } from 'react-native-gesture-handler';

import testImg from './test.png';
import backImg from './back.png';

export default class App extends React.Component {
    onTestMove(event) {
        this.testAnimRef.transitionTo({
            translateX: event.nativeEvent.translationX,
            translateY: event.nativeEvent.translationY,
        }, 0);

    }
    render() {
        return (
            <ImageBackground source={backImg} style={{ flex: 1 }} >
                <PanGestureHandler
                    key={`test`}
                    onGestureEvent={(e) => { this.onTestMove(e) }}
                    onHandlerStateChange={e => { }}
                >
                    <Animatable.View style={styles._animatable_view}
                        ref={((ref) => { this.testAnimRef = ref }).bind(this)}
                        useNativeDriver={true}
                    >
                        <Image source={testImg} style={styles._image} />
                    </Animatable.View>
                </PanGestureHandler>
            </ImageBackground>
        );
    }
}

const styles = StyleSheet.create({
    _image: {
        width: 50,
        height: 25,
        resizeMode: 'contain',
        backgroundColor: 'black',
        borderColor: 'gainsboro',
        borderWidth: 2,
    },
    _animatable_view: {
        position: "absolute",
        top: 200,
        left: 100,
    },
});