用2种颜色填充常规多边形

时间:2017-05-24 11:00:44

标签: c# winforms graphics polygon

我绘制了正多边形并将它们分成相等的部分。 就像这样:enter image description here

但我想用2种颜色填充它:

enter image description here

我该如何实现? 代码如何绘制多边形如下:

    Graphics g = e.Graphics;
    nPoints = CalculateVertices(sides, radius, angle, center);

    g.DrawPolygon(navypen, nPoints);
    g.FillPolygon(BlueBrush, nPoints);
    Point center = new Point(ClientSize.Width / 2, ClientSize.Height / 2);

    for(int i = 0; i < sides; i++) {
         g.DrawLine(new Pen(Color.Navy), center.X, center.Y, nPoints[i].X, nPoints[i].Y);

    }

    private PointF[] CalculateVertices(int sides, int radius, float startingAngle, Point center)
    {
        if (sides < 3) {
            sides = 3;
        }
            //throw new ArgumentException("Polygon must have 3 sides or more.");

        List<PointF> points = new List<PointF>();
        float step = 360.0f / sides;

        float angle = startingAngle; //starting angle
        for (double i = startingAngle; i < startingAngle + 360.0; i += step) //go in a circle
        {
            points.Add(DegreesToXY(angle, radius, center));
            angle += step;
        }

        return points.ToArray();
    }

    private PointF DegreesToXY(float degrees, float radius, Point origin)
    {
        PointF xy = new PointF();
        double radians = degrees * Math.PI / 180.0;

        xy.X = (int)(Math.Cos(radians) * radius + origin.X);
        xy.Y = (int)(Math.Sin(-radians) * radius + origin.Y);

        return xy;
    }

1 个答案:

答案 0 :(得分:2)

有几种方法,但最直接的方法是分别绘制不同颜色的多边形(三角形)。

为颜色承担List<T>

List<Color> colors = new List<Color> { Color.Yellow, Color.Red };

您可以在DrawLine来电之前添加此内容:

using (SolidBrush brush = new SolidBrush(colors[i%2]))
    g.FillPolygon(brush, new[] { center, nPoints[i], nPoints[(i+1)% sides]});

请注意我如何使用nPoints运算符包围colors%

enter image description here