【发布时间】:2021-02-18 13:28:01
【问题描述】:
我目前正在为我的 Expo 应用程序实现一个基于 react-native-svg 的绘图输入(这是对这个答案的轻微修改:link)。我使用PanResponder 来注册移动事件并创建不同的路径,然后当用户在视图上绘制时,我将这些路径显示为多个Polyline 元素,如下所示:
const GesturePath: React.FC<GesturePathProps> = ({
paths,
color,
width,
height,
strokeWidth,
}) => {
return (
<Svg height='100%' width='100%' viewBox={`0 0 ${width} ${height}`}>
{paths.map((path) => (
<Polyline
key={path.id}
points={path.points.map((p) => `${p.x},${p.y}`).join(" ")}
fill='none'
stroke={color}
strokeWidth={strokeWidth}
/>
))}
</Svg>
);
};
不幸的是,我制作的线条非常粗糙且参差不齐,我相信PanResponder.onPanResponderMove 处理程序的触发频率太低,无法满足我的需要(平均而言,它在 Android Pixel 4 模拟器上每 50 毫秒调用一次,我不确定是否我可以期待更多来自真实设备的信息)。
也许有比 PanResponder 更好的候选者来处理我的用例中的手势?
我已经实现了一个平滑功能(基于此答案link),该功能运行正常,但由于这些点彼此相距太远,用户的输入会明显失真。
这是一个没有平滑的例子:
在我的 GestureHandler 实现下面:
const GestureRecorder: React.FC<GestureRecorderProps> = ({ addPath }) => {
const buffRef = useRef<Position[]>([]);
const pathRef = useRef<Position[]>([]);
const timeRef = useRef<number>(Date.now());
const pathIdRef = useRef<number>(0);
const panResponder = useRef(
PanResponder.create({
onStartShouldSetPanResponder: () => true,
onStartShouldSetPanResponderCapture: () => true,
onMoveShouldSetPanResponder: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderMove: (event) => {
// workaround for release event
// not working consistently on android
if (Date.now() - timeRef.current > RELEASE_TIME) {
pathIdRef.current += 1;
pathRef.current = [];
buffRef.current = [];
}
timeRef.current = Date.now();
pathRef.current.push({
x: event.nativeEvent.locationX,
y: event.nativeEvent.locationY,
});
addPath({
points: calculateSmoothedPath(event),
id: pathIdRef.current,
});
},
// not working on Android
// release event is not consistent
// onPanResponderRelease: () => {
// pathIdRef.current += 1;
// pathRef.current = [];
// buffRef.current = [];
// },
})
).current;
const calculateSmoothedPath = (event: GestureResponderEvent) => {
// implementation
// ...
// see: https://stackoverflow.com/questions/40324313/svg-smooth-freehand-drawing
}
return (
<View
style={StyleSheet.absoluteFill}
collapsable={false}
{...panResponder.panHandlers}
/>
);
};
旁注
我没有在 PanResponder 上找到任何文档表明存在采样率配置选项,因此我完全愿意接受替代方案(甚至完全放弃 PanResponder + 原生 SVG 方法),只要我不必退出 expo 项目并且我可以控制布局(我不想使用带有特定 UI 的外部组件)。
我曾尝试使用 expo-pixi 库(特别是 Sketch 组件),但存储库似乎不再被维护,并且在使用它时,expo 客户端始终崩溃。
【问题讨论】:
标签: reactjs react-native drawing react-native-svg panresponder