Fill Octagon in C#

南楼画角 提交于 2019-12-07 01:12:28

I'll give you a different approach. Think about an octagon as an eight-sided blocky circle.

From the origin of a circle, you can calculate a point along the edge of a cicle given the angle t (in radians) and radius r using trigonometry.

x = r cos t
y = r sin t

You could apply this method the calculate the points of an octagon (or an equilateral shape with any number of sides) but it won't be able to deform (stretch). In order for it to deform, the formula changes slightly (where a is the horizontal radius and b is the vertical radius).

x = a cos t
y = b sin t

Here's what that might look like in code - I've modified your code in this instance.

public static void FillEquilateralPolygon(PaintEventArgs e, int sides, Color color, double x, double y, double width, double height)
{
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

    double a = width / 2;
    double b = height / 2;

    var points = new List<Point>();

    for (int pn = 0; pn < sides; pn++)
    {
        double angle = (360.0 / sides * pn) * Math.PI / 180;
        double px = a * Math.Cos(angle);
        double py = b * Math.Sin(angle);
        var point = new Point((int) (px + x), (int) (py + y));
        points.Add(point);
    }

    using (var br = new SolidBrush(color))
    {
        using (var gpath = new GraphicsPath())
        {
            gpath.AddPolygon(points.ToArray());
            e.Graphics.FillPath(br, gpath);
        }
    }
}

Now you can call this method, passing in 8 sides, and render an octogon that can deform.

FillEquilateralPolygon(e, 8, Color.Red, 201, 101, 201, 101);

If you don't want it to deform, just use the radius of the smallest side instead of replacing r with a and b.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!