简体   繁体   中英

How to dynamically create an overlay over a VB.Net PictureBox

I have a VB.Net PictureBox floorPlanImage on a form form1 .

I load a picture into the picturebox:

    floorPlanImage.image = my.resources.ResourceManager.GetObject("level8") 'this is actually dynamic, and this part works

I am trying to create an overlay to highlight a region of the image:

    Public Sub highlightPrintArea(ByVal x1 As Integer, ByVal y1 As Integer, ByVal x2 As Integer, ByVal y2 As Integer)
    '**** DOES NOT WORK
    Dim g As Graphics = Me.CreateGraphics
    Dim r As Rectangle = New Rectangle(x1, y1, x2 - x1, y2 - y1) 'these are args passed in to the function
    Dim pen As Pen = New Pen(Color.FromArgb(128, 32, 100, 200), 1) 'semi-transparent
    Dim b As Brush = New SolidBrush(pen.Color)

    g.FillRectangle(b, r)
    end sub

I need to do this dynamically at runtime, say, on button click. The above function does not seem to draw the rectangle.

However, if I have a function that Handles floorPlanImage.Paint like follows, then the rectangle is drawn as I expect it to:

Private Sub floorPlanImage_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles floorPlanImage.Paint
    '**** Works, but does not suit my workflow
    Dim g As Graphics = e.Graphics
    Dim r As Rectangle = New Rectangle(100, 100, 100, 100)
    Dim pen As Pen = New Pen(Color.FromArgb(128, 32, 100, 200), 1)
    Dim b As Brush = New SolidBrush(pen.Color)

    g.FillRectangle(b, r)
End Sub

The Question (finally)

How can I modify my onclick function to correctly overlay the rectangle over my PictureBox?

In the onclick event you need to save the location/point to a member variable and set a flag so app knows you have a location saved. To update the picture box call Invalidate and Update.

floorPlanImage.Invalidate()
floorPlanImage.Update()

In the onpaint event test the flag that you have a point then use the saved point to draw the overlay.

Private Sub floorPlanImage_Paint(ByVal sender As Object, ByVal e As  System.Windows.Forms.PaintEventArgs) Handles floorPlanImage.Paint
    If hasPoint

       'Draw with saved point
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM