在RN中用svg绘制三角形添加手势无法给予动画转换(Animated transform)
问题描述,在RN种直接给View使用PanResponder手势,参考官网给View一些动画是正常的,
如附件demo中的组件DeviceDrag。官网示例代码链接 https://reactnative.cn/docs/animations但我们是要给一些图形(正方形、三角形)手势及拖拽移动效果,
如svg画出的三角形,当前代码所绘制的便是三角形当前问题是:Svg的G/Polygon添加手势会有响应,但无法给予拖拽移动。或者可以说是无法给Animated适合的变换。有无大佬可以在技术上指点迷津下,多谢!感恩!
Code: Select all
const AnimatedPolygon = Animated.createAnimatedComponent(Polygon);
const AnimatedG = Animated.createAnimatedComponent(G);
/// SVG相关代码
const SvgItemMove = () => {
// item信息
const [item, setItem] = useState({"points":{"x":62.89,"y":240.31},"rotate":90,"type":"A","scale":1,"color":"#0CC5E3","index":0})
const l = (77.89 - 28.44)
const getItemPoints = (item) => {
const points = item.points
const a = item.scale;
if (item.type !== 'D') {
switch (item.rotate) {
case 0:
return [
[points.x, points.y],
[points.x - a * l, points.y + a * l],
[points.x + a * l, points.y + a * l]
]
case 90:
return [
[points.x, points.y],
[points.x - a * l, points.y - a * l],
[points.x - a * l, points.y + a * l]
]
case 180:
return [
[points.x, points.y],
[points.x - a * l, points.y - a * l],
[points.x + a * l, points.y - a * l]
]
case 270:
return [
[points.x, points.y],
[points.x + a * l, points.y - a * l],
[points.x + a * l, points.y + a * l]
]
default:
return [
[points.x, points.y],
[points.x - a * l, points.y + a * l],
[points.x + a * l, points.y + a * l]
]
}
} else {
return [
[points.x, points.y - a * l],
[points.x - a * l, points.y],
[points.x, points.y + a * l],
[points.x + a * l, points.y]
]
}
}
const pan = useRef(new Animated.ValueXY()).current;
const panResponder = useRef(
PanResponder.create({
onMoveShouldSetPanResponder: () => true,
onPanResponderMove: Animated.event([
null,
{ dx: pan.x, dy: pan.y }
]),
onPanResponderRelease: () => {
console.log("手势响应结束?" + JSON.stringify(pan))
const tempItem = item
// tempItem.points = {"x":62.89,"y":240.31}
/**
* 问题描述,直接使用PanResponder手势,参考官网给View一些动画是正常的,如组件DeviceDrag。https://reactnative.cn/docs/animations
* 但我们是要给一些图形(正方形、三角形)手势及拖拽移动效果,如svg画出的三角形,当前代码所绘制的便是三角形
* 当前问题是:添加手势会有响应,但无法给予拖拽移动
*/
tempItem.points = {"x":pan.x,"y":pan.y}
setItem(tempItem)
Animated.spring(pan, { toValue: { x: 0, y: 0 } }).start();
}
})
).current;
return (
<View style={anistyles.container}>
<Text style={anistyles.titleText}>Drag & Release this box!</Text>
<Svg
width={deviceWidth}
height={deviceHeight}
>
<AnimatedG
style={{
transform: [{ translateX: pan.x }, { translateY: pan.y }]
}}
{...panResponder.panHandlers}
>
<Polygon
// points={"62.89,240.31 13.439999999999998,190.86 13.439999999999998,289.76"}
points={getItemPoints(item).map(_ => `${_[0]},${_[1]}`).join(' ')}
stroke={"black"} // 边线颜色
strokeWidth="2"
fill={"white"}
>
</Polygon>
</AnimatedG>
</Svg>
</View>
)
}