javascript - Expo + React Native:在两种视图的坐标之间画线
问题描述
我目前正在使用这个模块:https ://github.com/mxmzb/react-native-gesture-detector 。我希望能够从创建的点画一条线。但是,它似乎只输出圆圈。
它有一个“创建手势”视图:
<View style={{ position: "relative", width: "100%", height: "100%" }}>
<GesturePath
path={gesture.map(coordinate => {
if (recorderOffset) {
return {
x: coordinate.x + recorderOffset.x,
y: coordinate.y + recorderOffset.y,
};
}
return coordinate;
})}
color="green"
slopRadius={30}
center={false}
/>
</View>
GesturePath 的定义如下:
const GesturePath = ({ path, color, slopRadius, center = true }: GesturePathProps) => {
const baseStyle: ViewStyle = {
position: "absolute",
top: center ? "50%" : 0,
left: center ? "50%" : 0,
opacity: 1,
};
return (
<>
{path.map((point, index) => (
<Animated.View
style={Object.assign({}, baseStyle, {
width: slopRadius,
height: slopRadius,
borderRadius: slopRadius,
backgroundColor: color,
marginLeft: point.x - slopRadius,
marginTop: point.y - slopRadius,
})}
key={index}
/>
))}
</>
);
};
当您在该视图上绘图时,它会使用点勾勒出路径,如下所示:
我希望它是一条平滑的线,而不是上面图像的一系列圆圈。
解决方案
您将需要像 Canvas 这样的东西来绘制线条而不是像素(使用视图)。React Native 目前没有 Canvas 实现。
在 expo 中执行此操作的最简单方法是使用该react-native-svg
库。
使用它,您可以使用以下实现从手势数据中绘制一条折线:
import Svg, { Polyline } from 'react-native-svg';
const GesturePath = ({ path, color }) => {
const { width, height } = Dimensions.get('window');
const points = path.map(p => `${p.x},${p.y}`).join(' ');
return (
<Svg height="100%" width="100%" viewBox={`0 0 ${width} ${height}`}>
<Polyline
points={points}
fill="none"
stroke={color}
strokeWidth="1"
/>
</Svg>
);
};
您还可以react-native-gesture-detector
使用内置的 React Native PanResponder在没有库的情况下记录手势。这是一个例子:
const GestureRecorder = ({ onPathChanged }) => {
const pathRef = useRef([]);
const panResponder = useRef(
PanResponder.create({
onMoveShouldSetPanResponder: () => true,
onPanResponderGrant: () => {
pathRef.current = [];
},
onPanResponderMove: (event) => {
pathRef.current.push({
x: event.nativeEvent.locationX,
y: event.nativeEvent.locationY,
});
// Update path real-time (A new array must be created
// so setState recognises the change and re-renders the App):
onPathChanged([...pathRef.current]);
},
onPanResponderRelease: () => {
onPathChanged(pathRef.current);
}
})
).current;
return (
<View
style={StyleSheet.absoluteFill}
{...panResponder.panHandlers}
/>
);
}
请参阅此小吃以了解将所有内容捆绑在一起的工作应用程序:https ://snack.expo.io/@mtkopone/draw-gesture-path
推荐阅读
- python - discord.py 试图删除用户的所有角色
- django - 模型字段如何使用用户 ID 自动字段
- linux - 在用户之间平均划分进程,linux内核编程
- r - 从 R 中的另一个列表创建具有值条件的新列表(子列表)
- python-3.x - s3 中的镶木地板工具无法使用 boto3 访问文件
- c++ - 如何每 x 秒调用一次函数但同时能够做一些事情
- javascript - JavaScript 中已解析 CSV 的数字列标题
- python - 我在 glMultiDrawArraysIndirect 函数中出了什么问题?
- javascript - 在 HTML 表中使用 Javascript 更改输入类型
- javascript - 将用户输入传递给服务器以进行 C++ 编译