动画移动x和y与软移动反应原生

问题描述 投票:0回答:1

我想在x和y轴上移动一个球,但是动画不是柔软的,运动是颤抖的,如果我移动得更快,它不会在对角线上精确移动,而是做一个角度我怎么能用软移动球?这是例子:

https://snack.expo.io/HJvm5WI5N

代码是:

import React from 'react';
import {Animated, StyleSheet, Text, TouchableOpacity, View} from 'react-native';

export default class App extends React.Component {

    constructor(props) {
        super(props)

        this.ball = new Animated.ValueXY({x: 30, y: 30})
    }

    moveBall = () => {
        Animated.timing(this.ball, {
            toValue: {x: 250, y: 350},
            duration: 2000
        }).start()
    }

    render() {
        return (
            <View style={styles.container}>
                <TouchableOpacity onPress={this.moveBall}>
                    <Animated.View style={[styles.ball, this.ball.getLayout()]}>
                        <Text style={styles.text}>+</Text>
                    </Animated.View>
                </TouchableOpacity>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
    },
    ball: {
        width: 60,
        height: 60,
        borderRadius: 30,
        backgroundColor: 'red',
        alignItems: 'center',
        justifyContent: 'center',
    },
    text: {
        fontWeight: 'bold',
        color: 'white',
        fontSize: 32
    }
});

react-native
1个回答
1
投票

您可以使用useNativeDriver来获得更好的性能。与translateX和translateY一起使用。因为你不能使用带有左右属性的useNativeDriver

constructor(props) {
        super(props)

        this.ball = new Animated.Value(0)
    }

    moveBall = () => {
        Animated.timing(this.ball, {
            toValue: 1,
            duration: 1000,
            useNativeDriver: true
        }).start()
    }


  render() {
    const xVal = this.ball.interpolate({
        inputRange: [0, 1],
            outputRange: [0, 250]
    });

    const yVal = this.ball.interpolate({
        inputRange: [0, 1],
            outputRange: [0, 350]
    })

    const animStyle = {
      transform: [{
        translateY: yVal, translateX: xVal
      }]
    }
    return (
      <View style={styles.container}>
                <TouchableOpacity onPress={this.moveBall}>
                    <Animated.View style={[styles.ball, animStyle]}>
                        <Text style={styles.text}>+</Text>
                    </Animated.View>
                </TouchableOpacity>
            </View>
    );
  }
© www.soinside.com 2019 - 2024. All rights reserved.