React Native实现一个渐变进度条

React Native实现一个渐变进度条_第1张图片

用ReactNative做一个渐变的进度条,可以用RN自带的ART画一个,也可以用SVG库来实现。今天,用自带的ART库实现一个渐变进度条。ART的用法就不细讲了,可以参考这个链接ARTDOC

1.新建一个React Native的测试工程

react-native init LineProgressBar

2.导入ART库(以iOS为例)

将 node_modules/react-native/Libraries/ART/ART.xcodeproj
添加到工程Libraries下 并连接libART.a

React Native实现一个渐变进度条_第2张图片
React Native实现一个渐变进度条_第3张图片
  1. 导入ART到js文件
import {
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    ART
} from 'react-native';

const {
    Surface,
    Group,
    Shape,
    LinearGradient,
    Path,
    Transform,
    ClippingRectangle
} = ART;

4.进度条需要个底色和进度的颜色咱们可以用ART的Group让他们整合在一起

  
    
        
        

    
 

5.下面画一个背景色

new Path()
    .moveTo(height / 2 + strokeWidth,  strokeWidth)
    .lineTo(width - height / 2 - strokeWidth, strokeWidth)
    .arcTo(width - strokeWidth, height/ 2 + strokeWidth)
    .arcTo(width - strokeWidth - height / 2, height + strokeWidth)
    .lineTo(height / 2 + strokeWidth, height + strokeWidth)
    .arcTo(strokeWidth, height / 2 + strokeWidth)
    .arcTo(height / 2 + strokeWidth, strokeWidth)
    .close()

6.实现一个渐变色

 new LinearGradient({
                '0': startColor,
                '1': endColor
            },
            '', "", this.props.style.width,  ''
        )

7.接下来实现一个动画。 运用RN的Animated来创建个动画组件。

 const AnimatedLineProgressBars = Animated.createAnimatedComponent(LineProgressBar);

8.用RN的Animated.timing 来实现动画效果

 Animated.timing(this.state.progressNumber, {
        toValue: progress,
        duration: 1000
    }).start();

实现动画的代码

componentDidMount() {
    this.startAnimate(this.props.progressNumber)
}

componentWillReceiveProps(nextProps) {
    if (nextProps != this.props && nextProps.progressNumber != this.props.progressNumber) {
        this.startAnimate(nextProps.progressNumber)
    }
}

startAnimate(progress) {
    this.state.progressNumber.setValue(0);
    Animated.timing(this.state.progressNumber, {
        toValue: progress,
        duration: 1000
    }).start();
}

render() {

    const {progressNumber, ...other} = this.props;

    return (
        
    )
}

调用代码

  

完整项目可查看:https://github.com/RoarRain/react-native-lineProgressBar-example

你可能感兴趣的:(React Native实现一个渐变进度条)