React Native利用Animated和SVG实现渐变进度条
根据项目需求,在React Native中实现渐变进度条的案例。
- 案例效果
- 案例分析
思路:将整个动画视图拆分成背景,进度,图文显示三个部分,分步实现,然后组合起来。
- 案例实现
1、需要使用的库,当然有些控件不需要下面的库也是可以实现的,这里采用是项目原因。
"react-native-svg": "^9.4.0",
"react-native-elements": "^1.1.0",
"react-native-vector-icons": "^6.4.2"
2、第一步实现背景,其实就是一个View,但是我这里采用SVG来画
<G fill="none" stroke={barBackGroundColor ? barBackGroundColor : '#D9E7DB'}>
<Path strokeWidth={height * 2} d="M0 0 L500 0" />
</G>
3、第二步实现渐变的进度条
实现方案:(界面+动画)
采用RN自带的库ART来实现,但是只支持iOS
采用第三方库SVG来实现,支持iOS和Android两个平台
界面实现:采用SVG库的LinearGradient来实现渐变效果,利用Animated实现动画
渐变进度实现关键代码
const AnimatePath = Animated.createAnimatedComponent(Path);
<Defs>
<LinearGradient id="grad" x1="0" y1="0" x2={width / 2} y2="0">
<Stop offset="0" stopColor={barStartColor ? barStartColor : "#D9E7DB"} stopOpacity="0" />
<Stop offset="1" stopColor={barEndColor ? barEndColor : "#89DE95"} stopOpacity="1" />
</LinearGradient>
</Defs>
<G fill="none" stroke="url(#grad)">
<AnimatePath strokeWidth={height * 2} d={this.lineAnimation} />
</G>
动画实现关键代码
this.lineAnimation = this.state.progressNumber.interpolate({
inputRange: [
0,
100
],
outputRange: [
`M0 0 L0 0`,
`M0 0 L375 0`,
]
});
startAnimate() {
const { isRepeat } = this.props;
this.state.progressNumber.setValue(0);
Animated.timing(
this.state.progressNumber,
{
toValue: this.props.style.width,
duration: 1000,
}
).start(isRepeat ? () => { this.startAnimate(0)} : null);
}
4、第三步实现连接成功后的图文显示
这一步其实就是简单的UI布局
<TouchableOpacity style={[styles.messageContainer, {height: height}]} activeOpacity={1} onPress={isAllowClick ? () => this.clickMessage() : null}
>
<Icon name={iconName} size={iconSize} color={iconColor} type={iconType} iconStyle={iconStyle ? iconStyle : styles.iconStyle}/>
<Text style={textStyle ? textStyle : styles.textStyle}>{message}</Text>
</TouchableOpacity>
5、第四步将上面的步骤组合起来
采用绝对布局的方式将第三步的UI视图覆盖到渐变进度条上面。
以上就是实现该按钮的思路了,三方库和动画的使用这里就不做讲解了。完整代码地址包括采用ART实现渐变进度条代码。
完成代码清单
TestVpnScreen 测试页面
VpnConnectView 封装的案例视图
AnimatedLineSVGProgressBar SVG实现的渐变进度条包括背景
LineProgressBarPage 测试页面
LineProgressBar ART实现渐变进度
AnimatedLineProgressBar 加上动画效果