【问题标题】:Fill regular polygons with 2 colors用 2 种颜色填充正多边形
【发布时间】:2017-05-24 11:00:44
【问题描述】:

我绘制了正多边形并将它们分成相等的部分。 是这样的:

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

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

    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;
    }

【问题讨论】:

  • 这不会编译:ClientSize/2.Width.X, ClientSize/2.Height.Y - 如果你想要两种颜色,基本上你需要两个多边形。 - 另外:您的目标是什么:Winforms、WPF、ASP..? 总是正确标记您的问题! - lso:尽量避免 List 的数组。使用起来更好!
  • @TaW 哦,我打错了,我正在使用 Winforms(编辑了我的问题!!)。我为两种颜色制作了颜色数组,但我不知道如何使用它..
  • 您可以通过PInvoke使用ExtFloodFill函数。

标签: c# winforms graphics polygon


【解决方案1】:

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

假设颜色为List&lt;T&gt;

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]});

请注意我是如何使用 % 运算符环绕 nPointscolors 的!

【讨论】:

  • 这个想法太棒了!非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-02
相关资源
最近更新 更多