ReactNative实现点赞飘心动画
前言
公司正在做直播项目,其中需要做一个类似YY,虎牙,斗鱼中的点赞飘心的动画.由于没有找到对应的库,就只能自己写一个了,目前采用的是ReactNative中的插值动画,其实实现起来也比较简单.上代码…
第一步
在构造函数中声明多个用来驱动动画的Animate变量,以及一个用来做视图于动画匹配的变量
constructor(props) {super(props)for (let i = 0; i < 10; i++) {this[`HeartArg${i}`] = new Animated.Value(0)}this.viewNum = 0}
第二步
在render函数中使用循环声明多个View,我这里使用的是10个图片来进行动画的循环,其中要注意的是ref属性,这里是为了后续设置随机颜色而设置的变量,其中的top,right, transform, opacity都使用了插值函数,不过大家也可以通过这种方式实现对其他属性的操作
<View>{Array(10).fill().map((_, index) => {return <Animated.Imagekey={index}ref={_ => this[`animImg${index}`] = _}style={[ChatRoomToolsSty.animImg, {top: this[`HeartArg${index}`].interpolate({inputRange: [0, 1, 2, 3],outputRange: [10, -100, -200, -300]}),right: this[`HeartArg${index}`].interpolate({inputRange: [0, 1, 2, 3],outputRange: Math.floor(Math.random() + 0.5) === 0 ? [7, 30, 15, 7] : [7, 0, 30, 10]}),transform: [{scale: this[`HeartArg${index}`].interpolate({inputRange: [0, 1, 2, 3],outputRange: [0.5, 1, 1.5, 1]})}],opacity: this[`HeartArg${index}`].interpolate({inputRange: [0, 1, 2, 3],outputRange: [0.5, 1, 0.5, 0]})}]}source={Images.action4}/>})}</View>
第三步
声明一个用来驱动动画的函数,其中的随机颜色用到了上一步中的ref声明, COLOR_ARR这个常亮根据产品需求可以自己定义一个数组
startAnimate = () => {this[`HeartArg${this.viewNum}`].setValue(0)//设置随机颜色let colorIndex = Math.floor(Math.random() * 10)this[`animImg${this.viewNum}`].setNativeProps({style: {tintColor: COLOR_ARR[colorIndex]}})//根据当前动画驱动值进行判断是否对新VIEW进行驱动let currentValue = this[`HeartArg${this.viewNum}`].__getValue()if (currentValue !== 0) {this.viewNum++}Animated.timing(this[`HeartArg${this.viewNum}`],{toValue: 3,duration: 2000,easing: Easing.linear}).start(() => {this[`HeartArg${this.viewNum}`].setValue(0)})//如果当前正在驱动的VIEW的数量大于8,则重置回0,让动画循环if (this.viewNum > 8) {this.viewNum = 0}this.viewNum++}
颜色数组可定义成下面这样👇
const COLOR_ARR = ['#9C89B8','#F0A6CA','#EFC3E6','#F0E6EF','#B8BEDD','#5BC0EB','#FDE74C','#9BC53D','#E55934','#FA7921'
]
第四步
定义一个Btn按钮,开始吧😁
<ChatRoomToolsActionBtnsource={Images.action4}onPress={() => {this.startAnimate()}}/>
看成品
如果觉得这些内容对你有用,那点个赞再走吧❤️,欢迎转发,还请注明出处,谢谢
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
