
用ReactNative做一個(gè)漸變的進(jìn)度條,可以用RN自帶的ART畫一個(gè),也可以用SVG庫(kù)來(lái)實(shí)現(xiàn)。今天,用自帶的ART庫(kù)實(shí)現(xiàn)一個(gè)漸變進(jìn)度條。ART的用法就不細(xì)講了,可以參考這個(gè)鏈接ARTDOC
1.新建一個(gè)React Native的測(cè)試工程
react-native init LineProgressBar
2.導(dǎo)入ART庫(kù)(以iOS為例)
將 node_modules/react-native/Libraries/ART/ART.xcodeproj
添加到工程Libraries下 并連接libART.a


- 導(dǎo)入ART到j(luò)s文件
import {
StyleSheet,
View,
Text,
TouchableOpacity,
ART
} from 'react-native';
const {
Surface,
Group,
Shape,
LinearGradient,
Path,
Transform,
ClippingRectangle
} = ART;
4.進(jìn)度條需要個(gè)底色和進(jìn)度的顏色咱們可以用ART的Group讓他們整合在一起
<Surface
width={this.props.style.width} height={this.props.style.height}
>
<Group>
<Shape
d={this.state.backgroundPath}
fill={'#F2F2F2'}
/>
<Shape
d={this.state.abovePath}
fill={this.state.barColor}
strokeWidth={this.props.strokeWidth}
stroke={this.props.strokeColor}
strokeCap={'butt'}
strokeJoin={'bevel'}
/>
</Group>
</Surface>
5.下面畫一個(gè)背景色
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.實(shí)現(xiàn)一個(gè)漸變色
new LinearGradient({
'0': startColor,
'1': endColor
},
'', "", this.props.style.width, ''
)
7.接下來(lái)實(shí)現(xiàn)一個(gè)動(dòng)畫。 運(yùn)用RN的Animated來(lái)創(chuàng)建個(gè)動(dòng)畫組件。
const AnimatedLineProgressBars = Animated.createAnimatedComponent(LineProgressBar);
8.用RN的Animated.timing 來(lái)實(shí)現(xiàn)動(dòng)畫效果
Animated.timing(this.state.progressNumber, {
toValue: progress,
duration: 1000
}).start();
實(shí)現(xiàn)動(dòng)畫的代碼
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 (
<AnimatedLineProgressBars
{...other}
progressNumber = {this.state.progressNumber}
/>
)
}
調(diào)用代碼
<AnimatedLineProgressBar
style={{
marginTop: 10,
height: 25,
width: width
}}
progressTotal={100}
progressNumber={90}
strokeWidth={0}
barStartColor={'orange'}
barEndColor={'purple'}
/>
完整項(xiàng)目可查看:https://github.com/RoarRain/react-native-lineProgressBar-example