你如何在React Native中实现捏合缩放?

11

我一直在研究PanResponder。我的目前的工作假设是,如果有两个正在向外移动的触摸点,我将在onPanResponderMove函数中检测到它们,并增加元素的大小。

这似乎是一种比较混乱的方法。是否有更流畅的方式?


1
我现在正在处理这个。我会告诉你我发现了什么。 - Jehan
@Jehan 有什么消息吗? :) - eden
@EnieJakiro,这个进展不太顺利。计算这个的数学很简单,但是JS似乎太慢/反应不及时了,无法保持一切正常运行。一直出现奇怪的反馈循环,缩放会变得非常大。更好的方法是本地编程捏合缩放,并为RN提供特殊的捏合缩放视图。 - Jehan
你可以尝试使用这个链接中的代码,我正在使用它且表现完美。 https://github.com/merryjs/photo-viewer - Mertcan Diken
5个回答

9
如果你只需要简单的缩放功能,可以使用ScrollView(文档在这里)。只需设置maximumZoomScale(大于1)和minimumZoomScale为所需值即可。

26
这个只适用于iOS,对吗?有没有办法让它在安卓上运行? - Dan Leveille
minimumZoomScalemaximumZoomScale是仅适用于iOS的属性。 - Andrew

7

注意:本答案与全局响应器无关,而是解答如何在React Native中实现捏合缩放的主要问题。

使用Expo或未使用Expo的React-Native,您可以从react-native-gesture-handler导入PinchGestureHandler。这里还有其他手势处理程序:react-native-gesture-handler

import { PinchGestureHandler } from 'react-native-gesture-handler';

举个例子,假设我们正在使用相机,并且希望检测捏合手势进行缩放:

<PinchGestureHandler
    onGestureEvent={this.onPinchGestureEvent}
  >
    <View>
          <Camera
              type={cameraType}
              flashMode={flashMode}
              zoom={zoom}
              style={styles.preview}
              ref={camera => this.camera = camera}
          />
    </View>
        </PinchGestureHandler>

那么我们可以这样使用手势事件来执行操作:
   onPinchGestureEvent = event => {
      console.log(event.nativeEvent.scale);
    }

1
谢谢!这个例子让我对理解'react-native-gesture-handler'的相关元素有了一个良好的开端。 - garykwwong

2
除了查看 Pan Responder,您还需要查看 Gesture Responder System
特别是响应器返回的evt。 这是React-Native文档中所说的。
evt is a synthetic touch event with the following form:

nativeEvent
    changedTouches - Array of all touch events that have changed         since the last event
    identifier - The ID of the touch
    locationX - The X position of the touch, relative to the element
    locationY - The Y position of the touch, relative to the element
    pageX - The X position of the touch, relative to the root element
    pageY - The Y position of the touch, relative to the root element
    target - The node id of the element receiving the touch event
    timestamp - A time identifier for the touch, useful for velocity calculation
    touches - Array of all current touches on the screen

现在您已经有了触摸功能,可以确定哪些区域/对象被触摸并相应地调整物品。

1
“node id”是什么?你怎么知道哪个组件有id? - Piotr

0

你需要使用手势响应系统

简单的捏合和缩放手势需要进行平移和缩放。

为了计算平移和缩放因子,你需要存储触摸事件并使用触摸位置增量。

我编写了一个NPM模块来实现这个功能。

react-native-pinch-zoom-responder


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接