我正在尝试通过svg绘制饼图,并且切片之间存在间隙/线,但目前无法获得正确的结果。 This的外观。
这是我完成组件的方法,这是参考了此medium帖子。
import React from 'react';
import { View, ViewPropTypes } from 'react-native';
import PropTypes from 'prop-types';
import Svg, { Path, G } from 'react-native-svg';
import { styleHelper } from '../../../helpers';
const maxPercentage = 100;
const generateCoordinates = (percent) => {
const a = (percent * 2 * Math.PI) / maxPercentage;
const x = Math.cos(a);
const y = Math.sin(a);
return [x, y];
};
const PieChart = ({ style, data, size }) => {
const radius = size / 2;
const viewBox = `-${radius} -${radius} ${size} ${size}`;
let cumulativePercent = 0;
return (
<View style={[style, { width: size, height: size }]}>
<Svg
width={size}
height={size}
viewBox={viewBox}
style={{ transform: [{ rotate: '-90deg' }] }}
>
{data.map((slice) => {
const largeArcFlag = slice.percent > (maxPercentage / 2) ? 1 : 0;
const xAxisRotation = 0;
const sweepFlag = 1;
const scaleValue = slice.percentScale / maxPercentage;
const [startX, startY] = generateCoordinates(cumulativePercent);
const [endX, endY] = generateCoordinates(cumulativePercent += slice.percent);
// Building the SVG
const m = `M ${startX * radius} ${startY * radius}`;
const a = (
`A ${radius} ${radius} ${xAxisRotation} ${largeArcFlag} ${sweepFlag} ${endX * radius} ${endY * radius}`
);
const l = 'L 0 0';
return (
<G
key={slice.id}
transform={`scale(${scaleValue})`}
>
<Path
d={`${m} ${a} ${l}`}
fill={styleHelper.renderStyle(slice.color)}
/>
</G>
);
})}
</Svg>
</View>
);
};
PieChart.propTypes = {
style: ViewPropTypes.style,
data: PropTypes.arrayOf(PropTypes.shape({
location: PropTypes.string,
leads: PropTypes.number,
percent: PropTypes.number,
percentScale: PropTypes.number,
color: PropTypes.string,
})).isRequired,
size: PropTypes.number.isRequired,
};
PieChart.defaultProps = {
style: {},
};
export default PieChart;
当前正在绘制圆形饼图,其中切片相对于最大值进行了缩放。当前没有线/间隙将切片分开。
任何评论或建议确实很有价值。谢谢!