Skip to content

Instantly share code, notes, and snippets.

@mosluce
Created June 3, 2016 09:56
Show Gist options
  • Save mosluce/e53efd6023f8f01f2029c92d1db2a43f to your computer and use it in GitHub Desktop.
Save mosluce/e53efd6023f8f01f2029c92d1db2a43f to your computer and use it in GitHub Desktop.
拖拉:進階版
import React, {Component} from 'react';
import {
View,
Animated,
PanResponder,
StyleSheet,
Text,
Dimensions
} from 'react-native';
const Window = Dimensions.get('window');
const CIRCLE_SIZE = 80;
class Viewport extends Component {
constructor(props) {
super(props)
this.state = {
pan : new Animated.ValueXY(),
center : {x:0, y:0},
};
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderMove: Animated.event([null, {
dx: this.state.pan.x, // x,y are Animated.Value
dy: this.state.pan.y,
}]),
onPanResponderRelease: (evt, gestureState) => {
this.updateCenter(gestureState)
},
onPanResponderMove: (evt, gestureState) => {
let center = this.state.center;
this.state.pan.x.setValue(gestureState.dx + center.x);
this.state.pan.y.setValue(gestureState.dy + center.y);
}
});
}
updateCenter({dx = 0, dy = 0}) {
let center = this.state.center;
let nx = center.x + dx;
let ny = center.y + dy;
if(nx >= 0) {
nx = (Window.width - CIRCLE_SIZE) / 2;
} else {
nx = - (Window.width - CIRCLE_SIZE) / 2;
}
Animated.spring(this.state.pan, {
toValue: {
x: nx,
y: ny
}
}).start();
this.setState(Object.assign(this.state, {
center: {
x: nx,
y: ny
}
}));
}
componentDidMount() {
this.updateCenter({});
}
render() {
return (
<View style={styles.container}>
<View style={{
position: 'absolute',
top: (Window.height - CIRCLE_SIZE)/2,
left: (Window.width - CIRCLE_SIZE)/2,
}}>
<Animated.View ref={(circle) => {this.circle = circle;}} {...this.panResponder.panHandlers} style={[this.state.pan.getLayout(), styles.circle]}></Animated.View>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container : {
flex: 1,
backgroundColor: 'rgb(255, 184, 0)'
},
circle: {
position: 'absolute',
width: CIRCLE_SIZE,
height: CIRCLE_SIZE,
borderRadius: CIRCLE_SIZE/2,
backgroundColor: 'rgb(200, 0, 0)',
}
})
export default Viewport;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment