Drawing a drag and drop rectangle in react native

Viewed 586

I need to create an image on my application on top of which a user can draw a rectangle to select an area of the image with its finger. I then need to obtain the the top left and bottom right coordinates of the rectangle.

I have searched the web for how to do this, but to no avail. Can anyone help?

Thank you.

1 Answers

I'd suggest looking into react-native PanResponder, or react-native-gesture-handler PanGestureHandler. It is a component that responds to touch input, and calculates the x and y values when you drag your finger, it will also tell you the distance travelled from where the finger started.

You can use this data and pass the x and y travel distance back into the width and height value of a View component to make it drag out a box with your finger.

EDIT:

Here's something I just put together as a bit of an experiment using react-native-gesture-handler.

enter image description here

import { View } from 'react-native';
import { GestureEvent, PanGestureHandler, PanGestureHandlerEventPayload } from 'react-native-gesture-handler';

const Test = () => {
  const [start, setStart] = useState<{ x: number; y: number }>(null);
  const [end, setEnd] = useState<{ x: number; y: number }>({ x: 0, y: 0 });
  const [dimensions, setDimensions] = useState<{ w: number; h: number }>({ w: 0, h: 0 });

  const onPress = (event: GestureEvent<PanGestureHandlerEventPayload>) => {
    const { x, y, translationX, translationY } = event.nativeEvent;
    if (!start) setStart({ x: y, y: x });
    setDimensions({ w: translationX, h: translationY });
  };

  const onEnd = () => {
    if (!start) return;

    setEnd(start);
    setStart(null);
  };

  return (
    <View style={{ flex: 1 }}>
      <PanGestureHandler onGestureEvent={onPress} onEnded={onEnd}>
        <View style={{ width: '100%', height: '100%', backgroundColor: 'red' }}>
          <View
            style={{
              position: 'absolute',
              backgroundColor: 'blue',
              top: start?.x ?? end?.x,
              left: start?.y ?? end?.y,
              width: dimensions?.w ?? 0,
              height: dimensions?.h ?? 0,
            }}
          />
        </View>
      </PanGestureHandler>
    </View>
  );
};

export default Test;
Related