父边界内的可拖动视图

时间:2017-11-14 17:03:58

标签: animation react-native react-animated

我正面临一项任务,我想在背景图像上放置一个可拖动的标记,然后在背景图像中获取标记的坐标。

我已经按照this整洁的教程使用Animated.ImagePanResponderAnimated.ValueXY制作了一个可拖动的标记。问题是我无法弄清楚如何限制可拖动视图仅在其父级(背景图像)的边界内移动。

非常感谢任何帮助:)

最好的问候 延

2 个答案:

答案 0 :(得分:3)

以下是使用react-native-gesture-responder进行此操作的一种方法。

import React, { Component } from 'react'
import {
  StyleSheet,
  Animated,
  View,
} from 'react-native'
import { createResponder } from 'react-native-gesture-responder'

const styles = StyleSheet.create({
  container: {
    height: '100%',
    width: '100%',
  },
  draggable: {
    height: 50,
    width: 50,
  },
})

export default class WorldMap extends Component {
  constructor(props) {
    super(props)

    this.state = {
      x: new Animated.Value(0),
      y: new Animated.Value(0),
    }
  }
  componentWillMount() {
    this.Responder = createResponder({
      onStartShouldSetResponder: () => true,
      onStartShouldSetResponderCapture: () => true,
      onMoveShouldSetResponder: () => true,
      onMoveShouldSetResponderCapture: () => true,
      onResponderMove: (evt, gestureState) => {
        this.pan(gestureState)
      },
      onPanResponderTerminationRequest: () => true,
    })
  }
  pan = (gestureState) => {
    const { x, y } = this.state
    const maxX = 250
    const minX = 0
    const maxY = 250
    const minY = 0

    const xDiff = gestureState.moveX - gestureState.previousMoveX
    const yDiff = gestureState.moveY - gestureState.previousMoveY
    let newX = x._value + xDiff
    let newY = y._value + yDiff

    if (newX < minX) {
      newX = minX
    } else if (newX > maxX) {
      newX = maxX
    }

    if (newY < minY) {
      newY = minY
    } else if (newY > maxY) {
      newY = maxY
    }

    x.setValue(newX)
    y.setValue(newY)
  }
  render() {
    const {
      x, y,
    } = this.state
    const imageStyle = { left: x, top: y }

    return (
      <View
        style={styles.container}
      >
        <Animated.Image
          source={require('./img.png')}
          {...this.Responder}
          resizeMode={'contain'}
          style={[styles.draggable, imageStyle]}
        />
    </View>

    )
  }
}

答案 1 :(得分:3)

我仅使用本机PanResponder和Animated库完成了另一种方法。它花费了许多步骤才能完成,并且很难根据文档确定,但是,它在两个平台上均能很好地工作,并且性能似乎不错。

第一步是找到父元素(在我的情况下是View)的高度,宽度,x和y。 View需要一个onLayout道具。 onLayout={this.onLayoutContainer}

这里是我获取父对象的大小然后将setState设置为值的函数,因此我可以在下一个函数中使用它。

`  onLayoutContainer = async (e) => {
    await this.setState({
      width: e.nativeEvent.layout.width,
      height: e.nativeEvent.layout.height,
      x: e.nativeEvent.layout.x,
      y: e.nativeEvent.layout.y
    })
    this.initiateAnimator()
  }`

这时,我在屏幕上有了父级的大小和位置,因此我做了一些数学运算并启动了一个新的Animated.ValueXY。我设置了我希望图像偏移的初始位置的x和y,并使用已知值将图像居中放置在元素中。

我继续使用适当的值设置panResponder,但是最终发现我必须对x和y值进行插值以提供可以在其中操作的边界,并“限制”动画以不超出那些边界。整个功能如下:

`  initiateAnimator = () => {
    this.animatedValue = new Animated.ValueXY({x: this.state.width/2 - 50, y: ((this.state.height + this.state.y ) / 2) - 75 })
    this.value = {x: this.state.width/2 - 50, y: ((this.state.height + this.state.y ) / 2) - 75 }
    this.animatedValue.addListener((value) => this.value = value)
    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: ( event, gestureState ) => true,
      onMoveShouldSetPanResponder: (event, gestureState) => true,
      onPanResponderGrant: ( event, gestureState) => {
        this.animatedValue.setOffset({
          x: this.value.x,
          y: this.value.y
        })
      },
      onPanResponderMove: Animated.event([ null, { dx: this.animatedValue.x, dy: this.animatedValue.y}]),
    })
    boundX = this.animatedValue.x.interpolate({
      inputRange: [-10, deviceWidth - 100],
       outputRange: [-10, deviceWidth - 100],
       extrapolate: 'clamp'
     })
    boundY = this.animatedValue.y.interpolate({
      inputRange: [-10, this.state.height - 90],
      outputRange: [-10, this.state.height - 90],
      extrapolate: 'clamp'
    })
  }`

这里重要的变量是boundX和boundY,因为它们是不会超出所需区域的内插值。然后,使用以下值设置我的Animated.Image:

` <Animated.Image
     {...this.panResponder.panHandlers}
     style={{
     transform: [{translateX: boundX}, {translateY: boundY}],
     height: 100,
     width: 100,
    }}
    resizeMode='contain'
    source={eventEditing.resource.img_path}
  />`

我最后要确定的是,动画尝试渲染之前,所有值都可用于动画,因此我在我的渲染方法中添加了一个条件,以首先检查this.state.width,否则,同时渲染一个虚拟视图。所有这些共同使我达到了预期的结果,但是就像我说的那样,要完成一件看起来如此简单的事情-“留在父母身边”,似乎太冗长/太复杂。

相关问题