jipot
jipot

Reputation: 84

How to Draw Lines Between Convex Hull Points

Assuming I have correctly calculated the convex hull points through the quickhull algorithm, I want to display the convex hull on a panel with lines. However, my current nested for loop displays a line through every single point calculated. Is there a way to draw lines between only the exterior points? My nested for loop incorrectly displays the lines as such:

enter image description here

I want to display only lines around the exterior (like a fence). How do I do this?

private void panel1_Paint(object sender, PaintEventArgs e)
{
    if (pointsClicked.Count() == 0)
    {

    }
    else
    {
        base.OnPaint(e);
        using (Graphics g = e.Graphics)
        {
            var p = new Pen(Color.Black, 3);


            // draw a line for each point created
            for (int i = 0; i < convexHullPoints.Count() - 1; i++)
            {
                for (int j = 0; j < convexHullPoints.Count(); j++)
                {
                    g.DrawLine(p, convexHullPoints[i], convexHullPoints[j]);
                }
            }
        }
    }
}

Upvotes: 1

Views: 666

Answers (1)

user3146587
user3146587

Reputation: 4320

Replace the two nested for loops with a single loop that iterates over all the edges of the convex hull polygon:

int n = convexHullPoints.Count();

// Draw the edges [P_{n-1},P_0], [P_0,P_1], ..., [P_{n-2},P_{n-1}]
for (int i = n - 1, j = 0; j < n; i = j++)
{
    g.DrawLine(p, convexHullPoints[i], convexHullPoints[j]);
}

Note: I am assuming here that the points in the convexHullPoints array are ordered along the convex hull which may not be the case. If they are not, there exists ways to reorder them (compute the barycenter of the points and sort the points by directed angle w.r.t the barycenter, for instance).

Upvotes: 2

Related Questions