如何在 React Native 中制作微调器?我想通过 PanResponder 旋转框

Posted

技术标签:

【中文标题】如何在 React Native 中制作微调器?我想通过 PanResponder 旋转框【英文标题】:How to make a spinner in React Native? I want to rotate box via PanResponder 【发布时间】:2020-09-26 14:31:37 【问题描述】:

我正在尝试在本机反应中使用 PanResponder 以便在其中心旋转一个框。到目前为止,这是我的代码:

class Spinner extends React.Component 

 pan = new Animated.ValueXY();
 panResponder = PanResponder.create(
   onMoveShouldSetPanResponder: () => true,
   onPanResponderGrant: () => 
    this.pan.setOffset(
      x: this.pan.x._value,
      y: this.pan.y._value
    );
   ,
   onPanResponderMove: Animated.event([
    null,
     dx: this.pan.x, dy: this.pan.y 
   ]),
   onPanResponderRelease: () => 
    this.pan.flattenOffset();
   

 );


 render() 

  const RotateValue = "10deg"

  return (

    <View style=styles.container>
      <Animated.View
        style=
          width:100,
          height:300,
          transform:[ rotate: RotateValue ]
        
        ...this.panResponder.panHandlers
      >
       <View style=styles.box />
      </Animated.View>
    </View>

  )

'''

在这个 const RotateValue 中,我试图使用 this.pan.x 和 this.pan.y 来转换成度数。我放了“10度”来证明它会旋转10度。但是我迷失在如何完成我打算做的事情上。

任何帮助将不胜感激。非常感谢。

【问题讨论】:

【参考方案1】:

我认为您正在寻找的是一种称为插值的东西。 你可以在这里找到更多信息:https://animationbook.codedaily.io/interpolate/#:~:text=The%20interpolate%20function%20allows%20animated,interpolate%20from%20other%20interpolate%20values.&text=What%20this%20is%20doing%20is,we%20are%20interpolating%20the%20opacity.

const RotateValue = this.pan.x.interpolate(
    inputRange: [0, 360],
    outputRange: ['0deg', '360deg'],
    extrapolate: 'clamp'
);

我知道这不是最准确或最好的答案,但我希望这对您有所帮助。

【讨论】:

谢谢。这无疑让我更接近我想要做的事情!因为它使用“this.pan.x”进行插值,所以当我从左向右滑动光标时它会旋转(也就是沿着屏幕的 x 轴。你知道一种结合“this.pan.x”和插值中的“this.pan.y”?再次感谢。 这完全取决于您希望微调器如何操作。例如,您可以将 pan.x 插入到 rotateX 并将 pan.y 插入到 rotateY。 我要做的只是让我的手指围绕其中心旋转微调器并让它跟随我的手指。换句话说,如果我的手指接触到微调器对象并绕其轴转了一圈,微调器将跟随我的手指。我做了一点工作,我使用了“Animated.add(this.pan.x, this.pan.y).interpolate”,它主要适用于屏幕的右上角。所以我又到了另一个十字路口。

以上是关于如何在 React Native 中制作微调器?我想通过 PanResponder 旋转框的主要内容,如果未能解决你的问题,请参考以下文章

如何在 RecyclerView 中制作动态微调器?

如何在 doInBackgroung() 时制作 android AsyncTask 加载微调器

iOS上的React Native相机显示空白屏幕

如何在 React Native 中单独显示日期时间选择器?

在 React-Native 中制作指南针

排毒测试时,React Native 在初始屏幕上超时完成