效果
前台代码
<Grid x:Name="grid" />
后台代码
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
namespace WpfApp
{
/// <summary>
/// Window3.xaml 的交互逻辑
/// </summary>
public partial class Window3 : Window
{
public Window3()
{
InitializeComponent();
string[] colorList = { "Red","Yellow","Green","#FF0000FF","Pink" };
for (int i = 0; i < colorList.Length; i++)
{
var color = (Color)ColorConverter.ConvertFromString(colorList[i]);
Paint(new Point(40, 40), 30, colorList.Length, i, new SolidColorBrush(color));
}
}
public void Paint(Point center, double radius, int num, int index, Brush brush)
{
double 每段弧度 = 2 * Math.PI / num;
double 起始弧度 = 每段弧度 * index;
double 终止弧度 = 每段弧度 * (index + 1);
var 起始弧度的X偏移 = Math.Sin(起始弧度);
var 起始弧度的Y偏移 = Math.Cos(起始弧度);
var 终止弧度的X偏移 = Math.Sin(终止弧度);
var 终止弧度的Y偏移 = Math.Cos(终止弧度);
Point 起点 = new Point(center.X + radius * 起始弧度的X偏移, center.Y - radius * 起始弧度的Y偏移);
Point 终点 = new Point(center.X + radius * 终止弧度的X偏移, center.Y - radius * 终止弧度的Y偏移);
string data = $"M{起点.X},{起点.Y} A{radius},{radius},0,0,1 {终点.X},{终点.Y}";
Path path = new Path();
path.Stroke = brush;
path.StrokeThickness = 5;
var converter = TypeDescriptor.GetConverter(typeof(Geometry));
path.Data = (Geometry)converter.ConvertFrom(data);
grid.Children.Add(path);
}
}
}