Skip to content

Instantly share code, notes, and snippets.

@saitbnzl
Created January 1, 2019 21:16
Show Gist options
  • Save saitbnzl/d164ddcd1789bf1bc0577d9b0e5a6261 to your computer and use it in GitHub Desktop.
Save saitbnzl/d164ddcd1789bf1bc0577d9b0e5a6261 to your computer and use it in GitHub Desktop.
React Native Pie Chart
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import Svg, {
Defs,
LinearGradient,
Stop,
G,
Path,
Ellipse,
Circle
} from 'react-native-svg'
const slices = [
{ percent: 0.1, color: 'red' },
{ percent: 0.65, color: 'green' },
{ percent: 0.2, color: 'blue' },
];
function getCoordinatesForPercent(percent, radius) {
const x = Math.cos(2 * Math.PI * percent);
const y = Math.sin(2 * Math.PI * percent);
return [x, y];
}
export default class RainbowCircle extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
let cumulativePercent = 0;
return (
<Svg height="300" width="300" viewBox="-1 -1 2 2" style={{backgroundColor: 'gray'}}>
<Defs>
<LinearGradient id="grad1" x1="0%" y1="0%" x2="100%%" y2="0%">
<Stop offset="0%" stopColor="rgb(255,255,0)" stopOpacity="1" />
<Stop offset="100%" stopColor="rgb(255,0,0)" stopOpacity="1" />
</LinearGradient>
<LinearGradient id="grad2" x1="50%%" y1="0%" x2="100%" y2="0%">
<Stop offset="0%" stopColor="rgb(255,0,0)" stopOpacity="1" />
<Stop offset="100%" stopColor="rgb(255,0,255)" stopOpacity="1" />
</LinearGradient>
</Defs>
{
slices.map(slice => {
const [startX, startY] = getCoordinatesForPercent(cumulativePercent,50);
// each slice starts where the last slice ended, so keep a cumulative percent
cumulativePercent += slice.percent;
const [endX, endY] = getCoordinatesForPercent(cumulativePercent,50);
// if the slice is more than 50%, take the large arc (the long way around)
const largeArcFlag = slice.percent > .5 ? 1 : 0;
const pathData = [
`M ${startX} ${startY}`, // Move
`A 1 1 0 ${largeArcFlag} 1 ${endX} ${endY}`, // Arc
`L 0 0`, // Line
].join(' ');
console.log({pathData})
return (
<Path d={pathData} fill={slice.color}/>
)
})
}
</Svg>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment