DNA180 DNA180 - 6 months ago 33
Vb.net Question

Display an image in picturebox from specific position

I have a picturebox that "works" as button. I have load an image map as background image, to use it for buttons conditions (click, hover etc).

As default, background image shows it's top left position, the first icon. Let's say, how can I move (x) to 32px and (y) to 64? Something like css styles

background-position: 32px 64px;
for example.

Answer

If you need to reposition the image then I wouldn't use a PictureBox, just a Panel or draw the image on the surface of the form.

It is possible though with the following code. Notice that it removes the PictureBox's Image so you are losing the functionality of a PictureBox.

Public Class Form1
    Private _moveIt As Boolean = False
    Private _coyote As Image

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        _coyote = PictureBox1.Image
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        _moveIt = True
        PictureBox1.Invalidate()
    End Sub

    Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
        If _moveIt = True Then
            PictureBox1.Image = Nothing
            e.Graphics.DrawImage(_coyote, New Rectangle(New Point(32, 64), _
                                                        New Size(_coyote.Width, _coyote.Height)))
        End If
    End Sub
End Class

To keep the PcitureBox's functionality (to use its Image property) you would have to create a new image which is a transformed version of the original image.

enter image description here

enter image description here

Comments