如何用n个切片画一个圆

我正在使用react-native-svg模块,我想画一个划分为n个切片的圆。 我的圆半径是41,其中心是(50,50) 例如,对于n = 6,我想绘制这样的内容:

如何用n个切片画一个圆

sunjianing1234 回答:如何用n个切片画一个圆

我一直在努力为您找到解决方案

但是我在此过程中学到了很多东西

基于this article

import Svg,{Path} from 'react-native-svg';

import React from 'react';
import {View,StyleSheet} from 'react-native';

export default class SvgExample extends React.Component {
  slice() {
    let slices = [];

  //option 1  Equal size pieces
    slices.push({percent: 0.25,color: 'blue'});
    slices.push({percent: 0.10,color: 'red'});
    slices.push({percent: 0.28,color: 'green'});
    slices.push({percent: 0.19,color: 'yellow'});


    //option 2  Different size pieces
    // const numberOfSlice = 6; //number for slice

    // const colorArr = ['red','green','yellow','blue']; //color the slice
    // for (let i = 0; i < numberOfSlice; i++) {
    //   slices.push({percent: 1 / numberOfSlice,color: colorArr[i] || 'gray'});
    // }

    let cumulativePercent = 0;

    function getCoordinatesForPercent(percent) {
      const x = Math.cos(2 * Math.PI * percent);
      const y = Math.sin(2 * Math.PI * percent);
      return [x,y];
    }

    let arr = [];
    arr = slices.map(slice => {
      const [startX,startY] = getCoordinatesForPercent(cumulativePercent);
      cumulativePercent += slice.percent;
      const [endX,endY] = getCoordinatesForPercent(cumulativePercent);
      const largeArcFlag = slice.percent > 0.5 ? 1 : 0;
      const pathData = [
        `M ${startX} ${startY}`,// Move
        `A 1 1 0 ${largeArcFlag} 1 ${endX} ${endY}`,// Arc
        'L 0 0',// Line
      ].join(' ');
      return <Path d={pathData} fill={slice.color} key={pathData} />;
    });
    return arr;
  }

  render() {
    return (
      <View
        style={[
          StyleSheet.absoluteFill,{alignItems: 'center',justifyContent: 'center'},]}>
        <Svg
          height="100"
          width="100"
          viewBox="-1 -1 2 2"
          style={{transform: [{rotate: '-90deg'}]}}>
          {this.slice()}
        </Svg>
      </View>
    );
  }
}

expo codesandbox

option 1 option 2

本文链接:https://www.f2er.com/2920866.html

大家都在问