.NET GDI +:绘制带圆角的线条

ber*_*hof 3 .net drawing gdi+ rounded-corners graphicspath

给定一个点数组,可以很容易地根据这些点绘制一条线,例如使用GraphicsPath类.

例如,以下几点...

[0]: (0,0)
[1]: (100,0)
[2]: (0,100)
[3]: (100,100)
Run Code Online (Sandbox Code Playgroud)

...描述了一个类似于Z的线.

但是接下来是挑战; 我需要绘制半径为10像素的圆角.在角落,我指的是线条中不是起点或终点的点.在这种情况下,有两个角(0,100)(100,0).

我玩过beziers,曲线和弧线,其中一些可能解决方案 - 我自己还没有找到它,因为我必须能够处理所有角度绘制的线条,而不仅仅是水平线条或垂直线条.

设置LineJoin所述的Pen目的是Round不充分的,因为这仅示出了具有较宽的笔.


编辑:为了澄清,我很清楚GraphicsPath类的bezier,曲线和弧功能.我正在寻找一些关于构建可以采用任意数量的点的算法的更具体的建议,并将它们与圆角串在一起.


我把以下函数放在一起,它返回一个表示带圆角的线的路径.该功能使用了LengthenLine功能,可在此处找到.

protected GraphicsPath GetRoundedLine(PointF[] points, float cornerRadius)
{
  GraphicsPath path = new GraphicsPath();
  PointF previousEndPoint = PointF.Empty;
  for (int i = 1; i < points.Length; i++)
  {
    PointF startPoint = points[i - 1];
    PointF endPoint = points[i];

    if (i > 1)
    {
      // shorten start point and add bezier curve for all but the first line segment:
      PointF cornerPoint = startPoint;
      LengthenLine(endPoint, ref startPoint, -cornerRadius);
      PointF controlPoint1 = cornerPoint;
      PointF controlPoint2 = cornerPoint;
      LengthenLine(previousEndPoint, ref controlPoint1, -cornerRadius / 2);
      LengthenLine(startPoint, ref controlPoint2, -cornerRadius / 2);
      path.AddBezier(previousEndPoint, controlPoint1, controlPoint2, startPoint);
    }
    if (i + 1 < points.Length) // shorten end point of all but the last line segment.
      LengthenLine(startPoint, ref endPoint, -cornerRadius);

    path.AddLine(startPoint, endPoint);
    previousEndPoint = endPoint;
  }
  return path;
}
Run Code Online (Sandbox Code Playgroud)

Rom*_*ias 6

这是我用来绘制圆角矩形的函数......从这里你可以计算出每条线的角度.

Public Sub DrawRoundRect(ByVal g As Graphics, ByVal p As Pen, ByVal x As Single, ByVal y As Single, ByVal width As Single, ByVal height As Single, ByVal radius As Single)
    Dim gp As GraphicsPath = New GraphicsPath
    gp.AddLine(x + radius, y, x + width - (radius * 2), y)
    gp.AddArc(x + width - (radius * 2), y, radius * 2, radius * 2, 270, 90)
    gp.AddLine(x + width, y + radius, x + width, y + height - (radius * 2))
    gp.AddArc(x + width - (radius * 2), y + height - (radius * 2), radius * 2, radius * 2, 0, 90)
    gp.AddLine(x + width - (radius * 2), y + height, x + radius, y + height)
    gp.AddArc(x, y + height - (radius * 2), radius * 2, radius * 2, 90, 90)
    gp.AddLine(x, y + height - (radius * 2), x, y + radius)
    gp.AddArc(x, y, radius * 2, radius * 2, 180, 90)
    gp.CloseFigure()
    g.DrawPath(p, gp)
    gp.Dispose()
End Sub
Run Code Online (Sandbox Code Playgroud)

希望这能帮助你在三角学中更难的部分;)