Home > Mobile >  Make an image movable in React
Make an image movable in React

Time:11-19

We simply want to make an image movable around the screen and then snap back to the middle, we have our code below and that's working fine currently styled with a blue box that you can move around, but we're unable to figure out how we can amend the blue box into being our image that we have required in.

import React, { useRef } from "react";
import { Animated, PanResponder, StyleSheet, View, Image } from "react-native";

const Users = [{id:"1", uri: require('./assets/present.jpeg'), keyword: 'present1'}]

const DraggableView = () => {
  const position = useRef(new Animated.ValueXY()).current;
  console.log(pan)
  const panResponder = PanResponder.create({
    onStartShouldSetPanResponder: () => true,
    onPanResponderMove: Animated.event([
      null,
      {
        dx: pan.x, // x,y are Animated.Value
        dy: pan.y,
      },
    ]),
    onPanResponderRelease: () => {
      Animated.spring(
        pan, // Auto-multiplexed
        { toValue: { x: 0, y: 0 } } // Back to zero
      ).start();
    },
  });

  return (
    <View style={styles.container}>
      <Animated.View
        {...panResponder.panHandlers}
        style={[pan.getLayout(), <Image source={require('./assets/present.jpeg')}/>}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  box: {
    backgroundColor: "#61dafb",
    width: 80,
    height: 80,
    borderRadius: 4,
  },
});

export default DraggableView;

CodePudding user response:

The <Image /> component should be a child of the <Animated.View /> component. Currently, you have it defined in the style prop which doesn't work.

const DraggableView = () => {
  const position = useRef(new Animated.ValueXY()).current;
  console.log(pan)
  const panResponder = PanResponder.create({
    onStartShouldSetPanResponder: () => true,
    onPanResponderMove: Animated.event([
      null,
      {
        dx: pan.x, // x,y are Animated.Value
        dy: pan.y,
      },
    ]),
    onPanResponderRelease: () => {
      Animated.spring(
        pan, // Auto-multiplexed
        { toValue: { x: 0, y: 0 } } // Back to zero
      ).start();
    },
  });

  return (
    <View style={styles.container}>
      <Animated.View
        {...panResponder.panHandlers}
        style={pan.getLayout()}
      >
        <Image source={require('./assets/present.jpeg')}/>
      </Animated.View>
    </View>
  );
};
  • Related