Question

I seem to have great difficulty in creating a draw pen line function whereby the user clicks a button to create a line then picks a point on the form and types in a length in a textbox, which will also become the length of the line, its self.

Could somebody help with this?

Was it helpful?

Solution

You must also consider the direction of the line. Here's some code to help you get started. You supply the start point, the length of the line, and the angle in degrees with zero degrees being towards the positive x axis. The method will return the x, y coordinates of the end point of the line:

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

This code assumes a standard Cartesian plane. Since the origin for a Windows Form is in the top left of the form and the positive Y axis goes down the form, you will have to adjust this code to make it work properly if you intend to use it to draw lines on the form.

On a Windows Form, the angle increases in a clockwise direction, so here is a updated version of the getEndPoint method which adjusts for this (not fully tested):

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))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top