React native 的色调颜色问题



我是React Native的新手,遇到了一个问题,当我想动画图像色调颜色时发生。我希望颜色能像动画一样随着时间逐渐改变。计时应该实现,但它只完成动画的第一帧,然后定格。然而,由于某种原因,当我只是改变'tintColor'为'backgroundColor'动画工作良好。

下面是我的代码:
import React from 'react';
import { useState } from 'react';
import { Text, View, TouchableHighlight, Dimensions, Component, Image, Animated } from 'react-native';
import PropTypes from 'prop-types';
function RGBtoCSS(rgb) {
return "rgb(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")";
}
class MyImage extends React.Component {
constructor(props) {
super(props);
this.anim = new Animated.Value(0);
this.animate();
}
animate() {
this.props.onPress();
Animated.timing(
this.anim,
{
toValue: 1,
duration: 500,
useNativeDriver: false
}
).start();
}
render() {
var style = {
width: 500,
height: 500,
resizeMode: 'stretch'
};
var col = this.anim.interpolate(
{
inputRange: [0, 1],
outputRange: [RGBtoCSS([0, 0, 0]), RGBtoCSS([140, 74, 140])]
});
return (
<Animated.Image source={this.props.img} style={{ ...style, tintColor: col }} />
);
}
}
MyImage.propTypes = { img: PropTypes.string.isRequired, onPress: PropTypes.func.isRequired, spacing: PropTypes.number.isRequired };
export default function App() {
return (
<View style={{
flex: 1,
backgroundColor: RGBtoCSS([255, 255, 255])
}}>
<MyImage img={{ uri: 'https://img.icons8.com/color/452/google-logo.png' }} onPress={() => { }} spacing={0} />
</View>
);
}

(演示可在https://snack.expo.dev/v0GeiLbOP获得)

我找到了一个解决方法。您可以将两个<Animated.Image>堆叠在一起,第一个图像为最终颜色,第二个图像为起始颜色。然后,您可以使用opacity在这两个图像之间创建褪色效果,这也可以很好地使用interpolate

import React from 'react';
import { useState } from 'react';
import { Text, View, TouchableHighlight, Dimensions, Component, Image, Animated } from 'react-native';
import PropTypes from 'prop-types';
function RGBtoCSS(rgb) {
return "rgb(" + rgb[0] + "," + rgb[1] + "," + rgb[2] +")";
}
class MyImage extends React.Component {
constructor(props) {
super(props);
this.anim = new Animated.Value(0);
this.animate();
}
animate() {
this.props.onPress();
console.log(this.anim)
Animated.timing(
this.anim,
{
toValue: 1,
duration: 500,
useNativeDriver: false
}
).start();
}
render() {
var style = {
width: 500,
height: 500,
resizeMode: 'stretch'
};
var col = this.anim.interpolate(
{
inputRange: [0, 1], 
outputRange: [1, 0]
});


return (
<View>
<Animated.Image source={this.props.img} style={{ ...style,tintColor: RGBtoCSS([140, 74, 140]) }} />
<Animated.Image source={this.props.img} style={{ ...style, opacity:col, transform:[{translateY:"-100%"}],  tintColor: RGBtoCSS([0, 0, 0]) }} />
</View>
);
}
}
MyImage.propTypes = { img: PropTypes.string.isRequired, onPress: PropTypes.func.isRequired, spacing: PropTypes.number.isRequired };
export default function App() {
return (
<View style={{
flex: 1,
backgroundColor: RGBtoCSS([255, 255, 255])
}}>
<MyImage img={{ uri: 'https://img.icons8.com/color/452/google-logo.png' }} onPress={() => { }} spacing={0} />
</View>
);
}

零食- https://snack.expo.dev/ZYulbKh3g

最新更新