React Native:如何优化动态生成的SVG路径平滑度及路径闭合问题?
React Native SVG绘图画布的卡顿与路径异常问题
我希望在React Native应用中添加绘图画布,但未找到维护良好的相关库。经参考一篇文章采用SVG实现后,整体效果尚可,但存在两个问题:
- 手指移动稍快时,生成的路径会卡顿生硬
- 手指移出视图后,路径会出现乱跳,无法正常闭合
以下是我的SVG实现代码:
function DrawingCanvas() { const [currentPath, setCurrentPath] = useState<string[]>([]); const [paths, setPaths] = useState<{ path: string[]; color: string }[]>([]); const onTouchMove = (event: GestureResponderEvent) => { const newPath = [...currentPath]; // 获取当前触摸位置 const locationX = event.nativeEvent.locationX; const locationY = event.nativeEvent.locationY; // 创建新路径点 const newPoint = `${newPath.length === 0 ? "M" : ""}${locationX.toFixed( 0 )},${locationY.toFixed(0)} `; // 添加新点到路径中 newPath.push(newPoint); setCurrentPath(newPath); }; const onTouchEnd = () => { const currentPaths = [...paths]; const newPath = { path: currentPath, color }; // 保存当前路径并清空临时路径状态 currentPaths.push(newPath); setPaths(currentPaths); setCurrentPath([]); }; return <View onTouchMove={onTouchMove} onTouchEnd={onTouchEnd} style={{ elevation: 5 }} > <Svg height={width - 16} width={width - 16}> <Path d={currentPath.join("")} stroke={color} fill={"transparent"} strokeWidth={2} strokeLinejoin={"round"} strokeLinecap={"round"} strokeOpacity={0.5} /> {paths.length > 0 && paths.map((item, index) => ( <Path key={`path-${index}`} d={item.path.join("")} stroke={item.color} fill={"transparent"} strokeWidth={2} strokeLinejoin={"round"} strokeLinecap={"round"} /> ))} </Svg> </View> } export default DrawingCanvas;
我尝试绘制圆形时的效果如下:
内容的提问来源于stack exchange,提问作者Tsabary
相关产品推荐
相关产品推荐

