In the following code a
gap
variable is declared to maintain a gap on the sides of the
Rectangle
. The scale is calculated as the
Maximum
value of the
ratio
of the
Widths and Heights
of
PictureBox
and
Rectangle
respectively.
To run the sample, create a
Windows Forms
application and replace the contents of the
Form1
code file with the following code and run the application.
Public Class Form1
Dim button1 As New Button()
Dim pictureBox1 As New PictureBox()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
button1.Text = "Draw Rectangle"
button1.Dock = DockStyle.Bottom
Controls.Add(button1)
AddHandler button1.Click, AddressOf button1_Click
pictureBox1.Dock = DockStyle.Fill
Controls.Add(pictureBox1)
pictureBox1.BackColor = Color.White
pictureBox1.Size = New Size(450, 400)
End Sub
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim gap As Integer = 20
Dim rectangle1 As New Rectangle(0, 0, 10000, 4500)
Dim scale As Double = Math.Max(rectangle1.Width / (pictureBox1.Width - gap * 2), _
rectangle1.Height / (pictureBox1.Height - gap * 2))
Dim scaledRectangle = New Rectangle(gap, gap, _
rectangle1.Width / scale, rectangle1.Height / scale)
Dim graphics1 As Graphics = pictureBox1.CreateGraphics()
graphics1.DrawRectangle(Pens.Red, scaledRectangle)
graphics1.Dispose()
End Sub
End Class