绘制具有指定大小(长度)的笔线

时间:2011-12-16 12:59:14

标签: vb.net textbox line pen

我似乎很难创建绘图笔线功能,用户单击按钮创建一条线然后在表单上选取一个点并在文本框中键入一个长度,这也将成为一个长度。线,它的自我。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您还必须考虑线的方向。这里有一些代码可以帮助您入门。您提供起点,线的长度和以度为单位的角度朝向正x轴。该方法将返回该行终点的x,y坐标:

Sub Main()

    Dim start As New PointF(0, 0)
    Dim length As Double = 10
    Dim degrees As Double = 45

    Dim endPoint As PointF = getEndPoint(start, length, degrees)

    Console.WriteLine("Start point: {0}", start)
    Console.WriteLine("Length: {0}", length)
    Console.WriteLine("Angle: {0}", degrees)
    Console.WriteLine("End point: {0}", endPoint)


    Console.WriteLine("Press ENTER to exit...")
    Console.ReadLine()
End Sub

Private Function getEndPoint(ByVal startPoint As PointF, ByVal length As Double, ByVal angleInDegrees As Double) As PointF
    Dim x As Double = startPoint.X + length * Math.Cos(degreesToRadians(angleInDegrees))
    Dim y As Double = startPoint.Y + length * Math.Sin(degreesToRadians(angleInDegrees))

    Return New PointF(CType(x, Single), CType(y, Single))
End Function

Private Function degreesToRadians(ByVal degrees As Double) As Double
    Return (Math.PI / 180.0) * degrees
End Function

此代码假定标准笛卡尔平面。由于Windows窗体的原点位于窗体的左上角,而正Y轴位于窗体的下方,因此如果您打算使用它在窗体上绘制线条,则必须调整此代码以使其正常工作。

在Windows窗体上,角度以顺时针方向增加,因此这里是getEndPoint方法的更新版本,可以针对此进行调整(未经过完全测试):

Private Function getEndPoint(ByVal startPoint As PointF, ByVal length As Double, ByVal angleInDegrees As Double) As PointF
    Dim x As Double = startPoint.X + length * Math.Cos(degreesToRadians(360.0 - angleInDegrees))
    Dim y As Double = startPoint.Y + length * Math.Sin(degreesToRadians(360.0 - angleInDegrees))