从特定位置在图片框中显示图像

时间:2016-02-28 11:25:11

标签: vb.net

我有一个图片框,"工作"作为按钮。我已将图像地图加载为背景图片,以将其用于按钮条件(点击,悬停等)。

默认情况下,背景图片会显示左上角位置,即第一个图标。让我们说,我怎样才能将(x)移动到32px和(y)到64?例如 css styles background-position: 32px 64px;

1 个答案:

答案 0 :(得分:2)

如果您需要重新定位图片,那么我就不会使用PictureBox,只使用Panel或在图片表面上绘制图像。

虽然可以使用以下代码。请注意,它会删除PictureBox的图像,因此您将失去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

要保留PcitureBox的功能(使用其Image属性),您必须创建一个新图像,它是原始图像的转换版本。

enter image description here

enter image description here