Home > Back-end >  Drawing a drag and drop rectangle in react native
Drawing a drag and drop rectangle in react native

Time:12-16

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.

CodePudding user response:

I'd suggest looking into 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