Search code examples
vb.netlabelpicturebox

How to post label in center of picture box?


I have a Picturebox contain image (sketchImage mode) and I want to make a transparent Label (contain number) in the center of picturebox

So to make the Label transparent i use Parent like this ( in form load event ) :

Label7.Parent = PictureBox2
Label7.BackColor = System.Drawing.Color.Transparent

but now i have problem ! when i start the app the label cituate in the bottom of picture box ? how to fix that !!


Solution

  • What I would suggest is that you place the Label exactly where you want it to be in the designer, then translate the Location when you change the Parent, i.e.

    Dim labelLocation = myLabel.PointToScreen(Point.Empty)
    
    myLabel.Parent = myPictureBox
    myLabel.Location = myPictureBox.PointToClient(labelLocation)
    

    When you add the Label in the designer, its Parent will be the form. The first line above gets the screen coordinates of the Label on the form. The second line moves the Label from the form to the PictureBox, which will move the Label to the same point relative to the top-left of the PictureBox as it was to the top-left of the form. The last line will move the Label back where it was, by translating those screen coordinates to client coordinates relative to the PictureBox.

    Here's an extension method you can use to do this for any control:

    Imports System.Runtime.CompilerServices
    
    Public Module ControlExtensions
    
        <Extension>
        Public Sub ChangeParentMaintainingAbsoluteLocation(source As Control, newParent As Control)
            Dim absoluteLocation = source.PointToScreen(Point.Empty)
    
            source.Parent = newParent
            source.Location = newParent.PointToClient(absoluteLocation)
        End Sub
    
    End Module
    

    Once that's added, either directly to your project or via reference and import, you can simply call that method on the control you want to move. In your case, that would be:

    Label7.ChangeParentMaintainingAbsoluteLocation(PictureBox2)
    

    EDIT:

    That said, if you specifically want a child control in the centre of its parent:

    Dim parentSize = parent.ClientSize
    
    child.Location = New Point((parentSize.Width - child.Width) \ 2,
                               (parentSize.Height - child.Height) \ 2)
    

    The ClientSize is used because some controls - most particularly forms - have borders and those borders may also be asymmetrical. A PictureBox is one control that may have a border, making the client size less than the overall size. Forms will generally have a border and the top is thicker than the bottom, so using ClientSize is even more important.