如何使用 React Native 在屏幕上绘图?

IT技术 javascript reactjs react-native
2021-05-25 19:17:07

我正在尝试在 React Native 中实现一个 android 绘图应用程序。我正在使用 PanResponder,但我不知道如何获取用户触摸过的部分的坐标。

我尝试使用,react-native-svg但我不知道将PanResponder对象放在哪里

class App extends React.Component {
  constructor(props){
    super(props);
    this._panResponder={};
    this._previousLeft = 0;
    this._previousTop = 0;
    this._circleStyles = {};
    this.circle = null;
  }
  componentWillMount(){
    this._panResponder = PanResponder.create({
            onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder,
      onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder,
      onPanResponderGrant: this._handlePanResponderGrant,
      onPanResponderMove: this._handlePanResponderMove,
      onPanResponderRelease: this._handlePanResponderEnd,
      onPanResponderTerminate: this._handlePanResponderEnd,
    });
    this._previousLeft = 20;
    this._previousTop = 84;
    this._circleStyles = {
      style: {
        left: this._previousLeft,
        top: this._previousTop,
        backgroundColor: 'green',
      }
    };
  }
  componentDidMount() {
    this._updateNativeStyles();
  }


 render() {
    return (
      <View style={styles.container}>
        <View style={styles.circle}
          ref={(circle) => {
            this.circle = circle;
          }}
          { ...this._panResponder.panHandlers }
        />
      </View>
    );
  }

  _highlight = () => {
    this._circleStyles.style.backgroundColor = 'blue';
    this._updateNativeStyles();
  }

  _unHighlight = () => {
    this._circleStyles.style.backgroundColor = 'green';
    this._updateNativeStyles();
  }

  _updateNativeStyles() {
    this.circle && this.circle.setNativeProps(this._circleStyles);
  }

  _handleStartShouldSetPanResponder() {
    return true;
  }

  _handleMoveShouldSetPanResponder() {
    return true;
  }

  _handlePanResponderGrant = (e, gestureState) => {
    this._highlight();
  }

    _handlePanResponderMove = (e, gestureState) => {
    this._circleStyles.style.left = this._previousLeft + gestureState.dx;
    this._circleStyles.style.top = this._previousTop + gestureState.dy;
    this._updateNativeStyles();
  }

  _handlePanResponderEnd = (e, gestureState) => {
    this._unHighlight();
    this._previousLeft += gestureState.dx;
    this._previousTop += gestureState.dy;
  }

}

在这个例子中,圆圈移动,但我希望它留下痕迹。这可以通过获取圆移动的点的坐标然后为该点添加颜色来完成。

1个回答

我看到的所有其他产品都有问题,尤其是在升级到 IOS14(测试版)时,我找不到任何适用于我的项目的产品。

相反,我基于纯 JavaScript 和 HTML Canvas 创建了自己的绘图组件。该组件具有透明背景,因此也可以覆盖在任何背景上。这也适用于在线和离线模式。

以最简单的形式,您可以像这样初始化

import RNDrawOnScreen from 'react-native-draw-on-screen';

<RNDrawOnScreen
   penColor={'#000'}
   strokeWidth={20}
/>

如果您为 penColor 和 strokeWidth 传入参数,它们将在更新时自动更改。您还可以调用 undo 和 clear 方法。

这是 Expo 友好的,适用于 IOS/Android,只有一个依赖项react-native-webview来呈现视图。

我为此创建了一个 npm 包,希望其他人可能会发现它有用。包中包含一个示例简单 expo 应用程序,它使用该组件并创建屏幕截图中显示的简单绘图应用程序。

https://www.npmjs.com/package/react-native-draw-on-screen

在此处输入图片说明