项目新增一个业务需求,需要用户可以通过手势进行签名,然后去研究了下react native的ART,最后搞出来个这个东西。
import React, { Component } from "react"
import {
View,
ART,
PanResponder,
Dimensions
} from "react-native"
let {
Surface,
Shape,
Path
} = ART;
let {
height: deviceHeight,
width: deviceWidth
} = Dimensions.get('window');
let path;
class Draw extends Component {
state = {
coordinates: [] // 线路
}
componentWillMount() {
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder,
onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder,
onPanResponderGrant: this._handlePanResponderGrant,
onPanResponderMove: this._onPanResponderMove,
onPanResponderRelease: this._handlePanResponderEnd,
onPanResponderTerminate: this._handlePanResponderEnd,
});
}
_handleStartShouldSetPanResponder = (e, gestureState) => {
// 响应触摸
return true;
}
_handleMoveShouldSetPanResponder = (e, gestureState) => {
// 响应移动
return true;
}
_handlePanResponderGrant = (e, gestureState) => {
// 响应移动操作
let coordinates = this.state.coordinates.concat([{
x: e.nativeEvent.locationX,
y: e.nativeEvent.locationY,
}])
this.setState({ coordinates })
}
_onPanResponderMove = (e, gestureState) => {
// 最近一次的移动距离
let coordinates = this.state.coordinates.concat([{
x: e.nativeEvent.locationX,
y: e.nativeEvent.locationY,
}])
this.setState({ coordinates })
}
_handlePanResponderEnd = () => {
// 结束触摸
}
render() {
path = Path()
this.state.coordinates.forEach(item => {
// ios获取的x,y有时候为0,android正常,这里需要处理一下
if (item.x && item.y) {
if (item.move)
path.moveTo(item.x, item.y)
else
path.lineTo(item.x, item.y)
}
})
return <View style={{ flex: 1 }}>
<View {...this._panResponder.panHandlers}>
<Surface width={deviceWidth} height={deviceHeight}>
<Shape d={path} stroke="#000000" strokeWidth={3}/>
</Surface>
</View>
</View>
}
}