Hi,@VKSB .Welcome to Microsoft Q&A.
In your Draw_Rectangle_Function subroutine, you are creating a new Bitmap and Graphics object every time it is called. This means that when you call it the second time, it replaces the existing image in the PictureBox with a new one, and only the second rectangle is drawn on the new image.
To draw multiple rectangles on the same image, you should create the Bitmap and Graphics objects once and pass them to the subroutine. Here's how you can modify your code:
Sub Draw_Rectangle_Function(ByRef Rectangles As Graphics, ByRef X1 As Integer, ByRef Y1 As Integer, ByRef X2 As Integer, ByRef Y2 As Integer, ByRef X3 As Integer, ByRef Y3 As Integer, ByRef X4 As Integer, ByRef Y4 As Integer)
Dim PenColor1 As New System.Drawing.Pen(System.Drawing.Color.Red)
Rectangles.DrawLine(PenColor1, X1, Y1, X2, Y2)
Rectangles.DrawLine(PenColor1, X3, Y3, X4, Y4)
Rectangles.DrawLine(PenColor1, X1, Y1, X3, Y3)
Rectangles.DrawLine(PenColor1, X2, Y2, X4, Y4)
End Sub
Private Sub DrawRectanglesFunction_Btn_Click(sender As Object, e As EventArgs) Handles DrawRectanglesFunction_Btn.Click
Dim BMP As New Bitmap(PictureBox1.Width, PictureBox1.Height)
Dim Rectangles As Graphics = Graphics.FromImage(BMP)
Draw_Rectangle_Function(Rectangles, 25, 25, 75, 25, 25, 75, 75, 75)
Draw_Rectangle_Function(Rectangles, 100, 25, 150, 25, 100, 75, 150, 75)
PictureBox1.Image = BMP
End Sub
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.