C# GraphicsPath drawing issues
I am trying to draw a GraphicsPath in my program, but it seems to have issues where it adds random spikes to the path. This seems to get worse the wider the path is. I have made some test code which can replicate this problem.
This code required a form with a PictureBox in it (PictureBox dimensions at least 630 x 1050), and a single button. The code is then as follows:
private void button1_Click(object sender, EventArgs e)
{
drawSomeLines();
pictureBox1.Refresh();
}
private void drawSomeLines()
{
//initialise the plot area:
Bitmap image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
pictureBox1.BackgroundImage = image;
Graphics g = Graphi开发者_如何学运维cs.FromImage(image);
//create a graphics path:
GraphicsPath gPath = new GraphicsPath();
//add sections to the path:
gPath.AddLine(587.310059F, 29.2261658F, 229.974731F, 668.2402F);
gPath.AddArc(new RectangleF(203.177338F,560.3876F,421.357F,421.357F), -(90 - 299.21382700000413F), -1.532426F);
gPath.AddArc(new RectangleF(203.177368F,560.3876F,421.357F,421.357F), -(90 - 297.72672132554612F), -1.53240252F);
gPath.AddLine(224.740067F,678.2186F, 76.6899643F,979.773865F);
//draw the path 3 times, at different widths:
g.DrawPath(new Pen(new SolidBrush(Color.FromArgb(100, Color.Blue)), 80), gPath);
g.DrawPath(new Pen(new SolidBrush(Color.Blue), 40), gPath);
g.DrawPath(new Pen(new SolidBrush(Color.Red), 2), gPath);
}
I have drawn the path here 3 times at different widths, which shows how the problem gets worse at larger widths.
Does anyone know why this happens, and how I might prevent it? Any ideas would be much appreciated.
Cheers,
Greg
You have probably figured this out by now, but this is why you are getting the 'spikes' in your line:
When you add the second arc to your graphicspath object, its startpoint occurs 'before' the endpoint of the first arc that you added. When this happens, the graphics path has to backtrack to start drawing the second arc and you end up with some very sharp and oddly shaped corners, especially at large line widths.
If you have gaps in your line, graphicspath does a good job of filling them in, but if you have overlap, the results are not so good.
If you change this line of code:
gPath.AddArc(new RectangleF(203.177338F,560.3876F,421.357F,421.357F), -(90 - 299.21382700000413F), -1.532426F);
to this:
gPath.AddArc(new RectangleF(203.177338F,560.3876F,421.357F,421.357F), -(90 - 299.21382700000413F), -1.0F);
it removes the overlap in your 2 arc segments and the graphicspath can then fill in the gap and draw a smooth segment without the undesirable corner effects that produce the 'spikes'.
From a display standpoint, it is much better to have gaps in your line, rather than having any overlaps.
精彩评论