在React-Native中制作指南针
Make compass in React-Native
本文关键字:指南针 React-Native 更新时间:2023-09-26
我想做一个指南针,但我不知道如何使用磁力计的数据。
这是我的类Compass:
class Compass extends Component {
constructor(props) {
super(props);
}
componentWillMount(){
this._animeRotation = new Animated.Value(0);
}
componentDidMount() {
this.startAnimation();
}
startAnimation() {
Animated.timing(this._animeRotation, {
toValue: this.props.magn, //<-- What put here?
duration: 1000,
}).start(() => {
this.startAnimation();
});
}
render() {
var interpolatedRotateAnimation = this._animeRotation.interpolate({
inputRange: [0, 100],
outputRange: ['0deg', '360deg']
});
return (
<View>
<Animated.View style={[styles.box, {transform: [{rotate: interpolatedRotateAnimation}]}]}>
<Image style={styles.box} source={require('./arrow.png')}></Image>
</Animated.View>
</View>
);
}
}
这是App类:
class App extends Component {
constructor(props) {
super(props);
this.state = {
magn: {
x: 0,
y: 0,
z: 0
}
};
}
componentDidMount() {
//I can get the gyroscope if is necessary
SensorManager.startMagnetometer(500);
// magn is a object with axis z,y and x
DeviceEventEmitter.addListener('Magnetometer', (magn) => this.setState({magn}));
}
render() {
return (
<View>
<Compass magn={this.state.magn.x}></Compass>
</View>
);
}
}
在这段代码中,箭头旋转但不像它应该的那样。我必须这么做吗?
这些数字只是相对于目前检测到的"磁北",它受到建筑物中任何含铁(如钢)材料的影响。所以你首先要确定什么是真北。
你还需要使用X, Y和Z键,并获得相对于手机的方向(如果它是水平或垂直持有,哪个方向是纵向或横向)。这个算法一点也不简单。
出于这个原因,我建议您使用现有的包来获取方向,而不是传感器数据包。他们做计算,并给你一个数字与标题,就像你似乎期望在你的动画代码。另一种可能性是查看这些包的开放源代码并复制计算。
如果你的React Native应用程序是与Expo,如果它是用Create React Native App
命令(CRNA),那么你可以使用Expo Location
。这里是[一个例子](https://github.com/martincarrera/expo-location-example在Github上),这里是文档(寻找标题部分)。
我最终制作了自己的包。查看一下:
https://github.com/firofame/react-native-compass-heading相关文章:
- React重新渲染但未显示正确的组件
- React组件等待所需道具进行渲染
- React中的数据集表示
- Webpack开发服务器和React服务器端渲染
- React Redux错误页面管理
- react.js中的密钥绑定
- 如何在react js中将值从一个组件发送到另一个组件
- React Native通过Navigator将用户输入数据传递到选项卡栏IOS中的组件
- React:按键的性能提升
- 如何在react js中从一个页面导航到另一个页面
- React组件-设置页面标题
- 为react组件传递道具的最佳方式
- 如何使用带有Preact的React路由器
- 使用Jest测试React Native应用程序
- 为什么我的点击事件没有使用 react js 触发
- React 15使用空字符串删除输入值
- react组件中的绑定方法
- 是否存在React Native“;WEB代码安全防护”;
- 如何在react js中移动第二个组件
- 在React-Native中制作指南针