Eric De Vault Eric De Vault - 1 year ago 106 Question

How do I scale and set the origin of a draw picturebox with xy coordinates

I have a series of X,Y coordinates generated from a triangulated method of measurements. I would like to draw lines to the X,Y coordinates on a picture box so the data entry can be validated. My code generates these x,y values to dynamically created textboxes and then draws them on the picture box. Currently it is working but the resulting lines are very small and they are not centered. How can I fix this? The picturebox1 is 500x500. Here is the code

Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
If Me.CheckBox1.Checked = True Then
Dim n As Integer
Dim g As Graphics
g = PictureBox1.CreateGraphics

Dim x, y, x1, y1 As String
x = Me.Controls.Item("myTextBoxX1").Text
y = Me.Controls.Item("myTextBoxY1").Text
x1 = Me.Controls.Item("myTextBoxX2").Text
y1 = Me.Controls.Item("myTextBoxY2").Text

Dim xi, yi, x1i, y1i As Integer

xi = Convert.ToDecimal(x)
yi = Convert.ToDecimal(y)
x1i = Convert.ToDecimal(x1)
y1i = Convert.ToDecimal(y1)

g.DrawLine(New Pen(ForeColor), xi, yi, x1i, y1i)
Dim x1a, y1a, x2a, y2a As String
Dim x1ai, y1ai, x2ai, y2ai As Integer
For n = 3 To Me.TextBoxABPts.Text
x1a = Me.Controls.Item("myTextBoxX" & n - 1).Text
y1a = Me.Controls.Item("myTextBoxY" & n - 1).Text
x2a = Me.Controls.Item("myTextBoxX" & n).Text
y2a = Me.Controls.Item("myTextBoxY" & n).Text

x1ai = Convert.ToDecimal(x1a)
y1ai = Convert.ToDecimal(y1a)
x2ai = Convert.ToDecimal(x2a)
y2ai = Convert.ToDecimal(y2a)

g.DrawLine(New Pen(ForeColor), x1ai, y1ai, x2ai, y2ai)
Next n

g.DrawLine(New Pen(ForeColor), x2ai, y2ai, xi, yi)
End If
End Sub

Answer Source

It will probably be easier to use .Net Point for working with coordinates. They consist of X and Y integer values. PointF is another structure that is based on singles. Either will work for you. Create a function that can transpose as scale coordinates.

Private Function ScaledPoint(Point As Point, Origin As Point, Optional Scale As Double = 1.0) As Point
    Return New Point(CInt(Origin.X + Point.X * Scale), CInt(Origin.Y + Point.Y * Scale))
End Function

In you application, define an origin and scale factor. For example:

Dim origin As New Point(200, 100) 'Moves all points 200 right, 100 down.
Dim scaleFactor As Double = 5 'Makes drawing 5 times larger.

Now where you call g.DrawLine, change it to something like:

Dim Point1 As New Point(x1ai, y1ai) 'There are lots of ways to do this.
Dim Point2 As New Point(x2ai, y2ai) 'This is only an example.
g.DrawLine(New Pen(ForeColor), ScaledPoint(Point1, origin), ScaledPoint(Point2, origin))

There are lots of ways to define Point1 and Point2.