Home Search   What's New Index Books Links Q & A Newsletter Banners   Feedback Tip Jar MSDN Visual Basic Community

Title Transform a Graphics object to map an area in world coordinates to device coordinates in VB .NET This example shows how to transform a Graphics object to map an area in world coordinates to device coordinates in VB .NET. This lets you specify a coordinate system that is easier for you to draw in. The example draws in the coordinate area (-2, -2)-(2, 2) and the transformation maps that to various destination rectangles. transform, Graphics object, Graphics, world coordinates, device coordinates VB.NET, Graphics

The MapGraphicsWindow subroutine maps a Graphics object from world coordinates to device coordinates. First it clears any current transformation in the Graphics object.

The program translates to move the center of the world coordinates to the origin, scales to make the world coordinate rectangle match the size of the device coordinate rectangle, and finally translates to move the origin to the center of the device coordinate rectangle.

```' Map the world coordinates wxmin, wymin, wxmax, wymax to
' the device coordinates dxmin, dymin, dxmax, dymax.
Public Sub MapGraphicsWindow(ByVal gr As Graphics, _
ByVal wxmin As Single, ByVal wymin As Single, ByVal wxmax _
As Single, ByVal wymax As Single, _
ByVal dxmin As Single, ByVal dymin As Single, ByVal dxmax _
As Single, ByVal dymax As Single)
' Clear any current transformation.
gr.ResetTransform()

' Translate the world coordinate center to the origin.
gr.TranslateTransform( _
-(wxmax + wxmin) / 2, _
-(wymax + wymin) / 2, _
MatrixOrder.Append)

' Scale.
Dim sx As Single = CSng((dxmax - dxmin) / (wxmax - _
wxmin))
Dim sy As Single = CSng((dymax - dymin) / (wymax - _
wymin))
gr.ScaleTransform(sx, sy, MatrixOrder.Append)

' Translate the origin to the device coordinate center.
gr.TranslateTransform( _
(dxmax + dxmin) / 2, _
(dymax + dymin) / 2, _
MatrixOrder.Append)
End Sub```

When it repaints, the main program uses subroutine MapGraphicsWindow to draw the same curve in seveal places. The following code shows how a PictureBox draws the curve on itself. It maps the world coordinate rectangle (-2, -2)-(2, 2) onto the PictureBox's client area. Note that it flips the device rectangle's Y coordinates so the world coordinates in the drawing increase upwards instead of downwards as in the PictureBox.

```Private Sub PictureBox1_Paint(...) Handles PictureBox1.Paint
' Map -2 <= X <= 2, -2 <= Y <= 2 to the PictureBox.
Dim gr As Graphics = e.Graphics
MapGraphicsWindow(gr, _
-2, -2, 2, 2, _
0, PictureBox1.ClientSize.Height - 1, _
PictureBox1.ClientSize.Width - 1, 0)

' Draw the curve.
DrawCurve(gr)
End Sub```