如何使用GDI +(C#,WinForms)绘制带路径渐变的弧

时间:2014-08-21 10:19:58

标签: c# winforms gdi+ gradient gdi

以下是我想要实现的结果:

enter image description here

它应该是基于矢量的,它可以是可扩展的。

这是我尝试使用PathGradientBrush创建它:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    double outerRadius = 120;
    double innerRadius = 110;
    PointF DistanceFromCenter(PointF center, double radius, double angle)        
    {
        double angleInRadians = angle * Math.PI / 180;
        return new PointF((float)(center.X + radius * (Math.Cos(angleInRadians))),
                          (float)(center.Y + radius * (Math.Sin(angleInRadians))));
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        GraphicsPath path = new GraphicsPath();
        Point centerPoint = new Point(this.Width / 2, this.Width / 2);
        path.AddLine(this.DistanceFromCenter(centerPoint, innerRadius, 0), this.DistanceFromCenter(centerPoint, outerRadius, 0));
        path.AddArc(new RectangleF(centerPoint.X - (float)outerRadius, centerPoint.Y - (float)outerRadius, (float)outerRadius * 2, (float)outerRadius * 2), 0, -180);
        path.AddLine(this.DistanceFromCenter(centerPoint, outerRadius, -180), this.DistanceFromCenter(centerPoint, innerRadius, -180));
        path.AddArc(new RectangleF(centerPoint.X - (float)innerRadius, centerPoint.Y - (float)innerRadius, (float)innerRadius * 2, (float)innerRadius * 2), (float)0, -(float)180);

        PathGradientBrush pthGrBrush = new PathGradientBrush(path);

        // Set the color at the center of the path to red.
        pthGrBrush.CenterColor = Color.FromArgb(255, 255, 0, 0);

        // Set the colors of the points in the array.
        Color[] colors = {
       Color.FromArgb(255, 0, 0, 0),
       Color.FromArgb(255, 0, 255, 0),
       Color.FromArgb(255, 0, 0, 255), 
       Color.FromArgb(255, 255, 255, 255),
       Color.FromArgb(255, 0, 0, 0),
       Color.FromArgb(255, 0, 255, 0),
       Color.FromArgb(255, 0, 0, 255),
       Color.FromArgb(255, 255, 255, 255),
       Color.FromArgb(255, 0, 0, 0),  
       Color.FromArgb(255, 0, 255, 0)};

        pthGrBrush.SurroundColors = colors;

        // Fill the path with the path gradient brush.
        g.FillPath(pthGrBrush, path);
    }
}

以下是我得到的结果:

enter image description here

1 个答案:

答案 0 :(得分:2)

如果有人在寻找这个问题,可以采取以下措施:link。 特别感谢Thorsten Gudera。