我怎样才能创造半色星?
<Image source={require('../star.png')}
style={{
height: '100%',
aspectRatio: 1,
tintColor: 'blue',
backgroundColor: 'transparent'
}} />
是否可以使用背景视图并将图像用作遮罩? 我尝试了以下但显然失败了。
<View style={styles.container}>
<View style={{
position: 'absolute',
backgroundColor: 'blue',
width: '80%',
height: '100%'
}} />
<Image source={require('../star.png')}
style={{
height: '100%',
aspectRatio: 1,
tintColor: 'transparent',
}} />
</View>
答案 0 :(得分:2)
您可以使用此组件执行此操作。但是你应该找到一个明星的良好形象,星星必须用一种颜色填充,而恒星的背景颜色必须是透明的。我假设在这个例子中每个星30的宽度。您应该将费率值作为prop
export default class starRate extends Component {
render() {
return (
<View style={{height: 30, width: 150}}>
<View style={{
position: 'absolute',
backgroundColor: 'yellow',
height: 30,
width: this.props.rate*30,
}} />
<Image source={require('../star.png')}
style={{
position: 'absolute',
left: 0,
top: 0,
height: 30,
width: 150,
}} />
</View>
);
}
}
答案 1 :(得分:0)
根据接受的答案想法,我提出了类似的解决方案:
const colors = {background: 'white', color: 'yellow'};
const starIcon = require('../../img/star.png');
const Star = ({rating, inx, size, style} : {rating: number, inx: number, size: number, style: object}) => {
const emptyIcon = {width: size, height: size, tintColor: colors.background};
const fullIcon = {width: size, height: size, tintColor: colors.button};
if(rating >= inx) { return (<Image source={starIcon} style={[ style, fullIcon ]} />); }
if(rating <= inx-1) { return (<Image source={starIcon} style={[ style, emptyIcon ]} />); }
const width = ((rating + 1 - inx) * size) | 0;
return (
<View style={style}>
<Image source={starIcon} style={[emptyIcon]} />
<View style={{ width: width, height: size, overflow: 'hidden', position: 'absolute'}}>
<Image source={starIcon} style={[fullIcon]} />
</View>
</View>
);
};
const StarsRating = ({rating} : {rating: number}) => {
return (
<View style={styles.container}>
<Star rating={rating} inx={1} size={20} style={styles.icon} />
<Star rating={rating} inx={2} size={20} style={styles.icon} />
<Star rating={rating} inx={3} size={20} style={styles.icon} />
<Star rating={rating} inx={4} size={20} style={styles.icon} />
<Star rating={rating} inx={5} size={20} style={styles.icon} />
</View>
)
};
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
backgroundColor: 'transparent',
alignItems: 'flex-start',
},
icon: {
marginLeft: 2,
}
});