反应原生动画 - 在触摸位置启动动画



我在React Native中玩动画。想要构建一个允许用户随时触摸屏幕的屏幕。当他们这样做时,应该在他们的手指位置出现一个圆圈,并跟随它。当它们释放时,圆圈应该缩小到虚无。

我开始遵循本教程,该教程适用于类似弹簧的动画,其中您拖动一个预先存在的正方形(从屏幕中央开始(,它会在发布时重新弹出。

就我而言,圆圈应该没有预先存在的位置,这导致了问题。如果我初始化我的组件状态,比如说,pan: new Animated.ValueXY(),然后触摸屏幕,圆圈从左上角开始,而不是我的手指所在的地方。我已经尝试了各种其他解决方案,都替换了下面 onPanResponderGrant 方法中的注释行,但似乎无法弄清楚。

如何获得一个动画,只是让组件跟踪我的手指而不开始或返回任何地方?

下面是组件的代码:

class FollowCircle extends React.Component {
constructor(props) {
super(props);
this.state = {
pan: new Animated.ValueXY(),
scale: new Animated.Value(0)
};
}
componentWillMount() {
this._panResponder = PanResponder.create({
onStartShouldSetPanResponderCapture: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderGrant: (e, gestureState) => {
// This is the line I'm playing with
this.state.pan.setValue({ x: this.state.pan.x._value, y: this.state.pan.y._value });
Animated.spring(
this.state.scale,
{ toValue: 1, friction: 3 },
).start();
},
onPanResponderMove: Animated.event([
null, { dx: this.state.pan.x, dy: this.state.pan.y }
]),
onPanResponderRelease: (/* e, gestureState */) => {
this.state.pan.flattenOffset();
Animated.spring(
this.state.scale,
{
toValue: 0,
friction: 10,
restDisplacementThreshold: 1
},
).start();
}
});
}
render() {
const { pan, scale } = this.state;
const circleStyles = {
backgroundColor: 'black',
width: 50,
height: 50,
borderRadius: 25,
transform: [
{ translateX: pan.x },
{ translateY: pan.y },
{ scale }
]
};
return (
<AppWrapper navigation={ this.props.navigation }>
<Animated.View
style={ {
flex: 1,
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
backgroundColor: 'white'
} }
{ ...this._panResponder.panHandlers }
>
<Animated.View
style={ circleStyles }
/>
</Animated.View>
</AppWrapper>
);
}
};

这是我的替代尝试(替换注释行(:

this.state.pan.setValue({ x: gestureState.x0, y: gestureState.y0 });

而这个:

if (this.state.pan) {
this.state.pan.setValue({ x: this.state.pan.x._value, y: this.state.pan.y._value });
} else {
this.setState({ pan: new Animated.ValueXY(gestureState.x0, gestureState.y0) });
}

两者的行为似乎相似,每次移动后都会重置左上角的圆圈位置,除非我从该原点开始触摸,否则不会完全跟踪我的手指位置。

任何想法如何正确做到这一点?

我最终通过用页面大小的TouchableHighlight替换panResponder的东西来解决这个问题,并带有onTouch事件。

该事件触发了以下函数,该函数获取nativeEvent.pageXpageY位置,并使用该位置。我不得不对y位置进行一些细微的更改,以使其跨手机工作:

triggerSwipe({ nativeEvent }) {
const coordinates = { x: nativeEvent.pageX, y: nativeEvent.pageY };
const self = this;
if (!this.state.animating) {
this.setState({
x: coordinates.x,
y: coordinates.y + (this.windowHeight / 2.5),
animating: true
}, () => {
Animated.timing(
self.state.scale,
{ toValue: 20, duration: 600 },
).start(() => {
this.setState({
scale: new Animated.Value(0.01), // See Notes.md for reasoning
colorIndex: this.state.colorIndex + 1,
animating: false
});
});
});
}

动画圆圈是TouchableHighlight内部的一个Animated.View,它被馈送触摸的坐标。

最新更新