我正在尝试在 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;
}
}
在这个例子中,圆圈在移动,但我希望它留下轨迹。这可以通过获取圆圈移动的点的坐标然后为该点添加颜色来完成。
最佳答案
我遇到了所有我能看到的其他产品的问题,尤其是在升级到 IOS14(测试版)时,我找不到任何对我的项目有效的产品。
我改为基于纯 JavaScript 和 HTML Canvas 创建了自己的绘图组件。该组件具有透明背景,因此也可以叠加到任何背景上。这也适用于在线和离线模式。
最简单的形式你可以这样初始化
import RNDrawOnScreen from 'react-native-draw-on-screen';
<RNDrawOnScreen
penColor={'#000'}
strokeWidth={20}
/>
如果您为 penColor 和 strokeWidth 传入一个参数,它们将在更新时自动更改。您还可以调用撤消和清除方法。
这是 Expo 友好的,并且在 IOS/Android 上工作,只有 react-native-webview
的一个依赖项才能呈现 View 。
我为此创建了一个 npm 包,希望其他人会觉得它有用。包中包含一个示例简单的 expo 应用程序,它使用该组件并创建屏幕截图中显示的简单绘图应用程序。
关于javascript - 如何用 React Native 在屏幕上绘图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42759560/