2017-08-24 73 views

回答

1

视差效果在于不同的速度运动图像和在相同方向上,使得“接近”的目的是,它移动的速度越快,这产生三个维度的错觉。

要在反应本机中实现此效果,可以使用Animated库将一个图像的位置作为另一个图像位置的一部分进行插值。

有关示例起见,让我们假设要在垂直方向上的视差效应,并且所有图像被垂直地定位在0。

首先,你会在你的组件的状态需要一个动画值:

this.state = { 
    ... 
    imagePos: new Animated.Value(0) 
} 

然后,对于每个Image风格,你可以添加在其y轴上的变换:

<Animated.Image src={...} style={[firstImageStyle, { 
     transform: [{translateY: this.state.imagePos.interpolate({ 
      inputRange: [0, 1], 
      outputRange: [0, 100] 
     })}] 
    }]} 

<Animated.Image src={...} style={[secondImageStyle, { 
     transform: [{translateY: this.state.imagePos.interpolate({ 
      inputRange: [0, 1], 
      outputRange: [0, 50] 
     })}] 
    }]} 

注使用Animated.Image而不是Image来使图像具有生动性。

imagePos的值介于0和1之间时,会导致第一个图像在0-100 dp之间水平移动,第二个图像在0-50 dp之间移动。

要更改动画值的值,您可以使用Animated库中的任何函数(定时,弹簧,衰减等),或者将其附加到某个本地事件。

动画库文档有更多的细节。对于陀螺仪的使用,我没有深入细节,但你可以使用react-native-sensorsreact-native-motion-manager来获得你需要的值,并将它们附加到动画中。

+0

想你的解决方案,但'imagePos:Animated.Value(0)'抛出一个错误。 '不能调用类的function' – Lemoncide

+0

@Lemoncide忘了'new',编辑这个工作完全再加上Animated.timing属性和反应本地传感器库答案 – Kraylog

+0

。正是我需要的。 – Lemoncide

0

通过使用包像https://github.com/react-native-sensors/react-native-sensors我设法拿到了X,Y,Z的手机位置的值,并以动画的图像。

constructor() { 
    super(); 
    this.state = { 
     x: 0, 
     y: 0, 
     z: 0, 
    }; 
    } 

    componentWillMount() { 
    // Normal RxJS functions 
    accelerationObservable 
     .subscribe(({x, y, z}) => this.setState({ 
      x: x, 
      y: y, 
      z: z, 
     })); 
    } 

    render() { return (
     <Image style={{left: this.state.x + this.state.y, top: this.state.z}} 
        source={require('image.png')}/> 
    ) 
    } 
相关问题