在 React Native 中创建视差图像
我正在尝试在 React-Native 中创建动画视差"图像.我有一个静态背景图像和两个单独的图像作为叠加层.目标是创建类似于本网站上的图像http://www.digitalhands.net/ 或 https://www.galaxia.co/.我从哪里开始呢?最初我会很高兴它只从左到右移动等等.之后我想让它使用陀螺仪来获取 x 和 y 值来为图像设置动画.
I'm trying to create an animated "parallax" image in React-Native. I have a static background image and two individual images as an overlay. The goal is to create something similar to the image found on this website http://www.digitalhands.net/ or https://www.galaxia.co/. Where do I even start with this? Initially I'd be happy with it moving just on itself from left to right and etc. Afterwards I want to make it so that it would use the gyroscope to get the x and y values for animating the image.
视差效果由以不同速度和相同方向移动的图像组成,这样一个物体越靠近",它移动得越快,这就产生了三个维度的错觉.
A parallax effect consists of images moving in different speeds and in the same direction, such that the 'closer' an object is, the faster it moves, which creates the illusion of three dimensions.
要在 react-native 中实现这种效果,可以使用 Animated 用于将一个图像的位置插入为另一图像位置的一部分的库.
To achieve this effect in react-native, you can use the Animated library to interpolate the position of one image as a fraction of the position of another.
举个例子,假设您想要垂直方向的视差效果,并且所有图像都垂直定位为 0.
For the sake of an example, let's assume you want the parallax effect in the vertical direction, and that all images are positioned at 0 vertically.
首先,您需要一个组件状态的动画值:
First, you would need an animated value in your component's state:
this.state = {
...
imagePos: new Animated.Value(0)
}
然后,对于每个 Image
样式,您可以在其 y 轴上添加一个变换:
Then, for each Image
style you can add a transform on its y axis:
<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
来使图像具有动画效果.
Note the use of Animated.Image
instead of Image
to make the image animatable.
当 imagePos
的值在 0 和 1 之间时,这将导致第一张图像在 0-100 dp 之间水平移动,而第二张图像在 0-50 dp 之间移动.
This would cause the first image to move horizontally between 0-100 dp when imagePos
has values between 0 and 1, and the second image to move between 0-50 dp.
要更改动画值的值,您可以使用 Animated
库中的任何函数(时序、弹簧、衰减等),或者您可以将其附加到某个原生事件.
To change the value of the animated value you can use any of the functions in the Animated
library (timing, spring, decay, etc.) or you can attach it to some native event.
动画库文档有更多细节.
The animated library documentation has much more detail.
关于陀螺仪的使用,我没有细说,不过你大概可以用react-native-sensors 或 react-native-motion-manager 获取您需要的值,并将它们附加到动画中.
As for the use of the gyroscope, I haven't gone into the details, but you can probably use react-native-sensors or react-native-motion-manager to get the values you need, and attach them to the animation.