消失的Picturebox图像

时间:2018-01-29 01:30:23

标签: vb.net image

我成功地将文件中的图像加载到visual basic中的图片框中。或者我想。我在代码中有一个msgbox,图片显示在图片框中。拿出msgbox没有图片。有任何想法吗?感谢

    Private Sub DrawImageinSquarePanel(Panelname As PictureBox, ImageFile As String)
    g = Panelname.CreateGraphics() 'creates new graphics element in panel
    Dim newImage As Image = Image.FromFile(ImageFile) ' Create image.
    Dim SquareDim As Integer 'Size of longest dimension in source image

    If newImage.Width > newImage.Height Then
        SquareDim = newImage.Width
    Else
        SquareDim = newImage.Height
    End If

    MsgBox(Panelname.Width & "   " & Panelname.Height) 'the magic msgbox!!

    ' scale factor
    Dim imageAttr As New ImageAttributes
    imageAttr.SetGamma(Panelname.Width / SquareDim)
    Dim ScaleFactor As Single = Panelname.Width / SquareDim

    ' Create rectangle for source and destination image.
    Dim srcRect As New Rectangle(0, 0, newImage.Width, newImage.Height)
    Dim destRect As New Rectangle((Panelname.Width - newImage.Width * ScaleFactor) / 2, (Panelname.Height - newImage.Height * ScaleFactor) / 2, newImage.Width * ScaleFactor, newImage.Height * ScaleFactor)
    Dim units As GraphicsUnit = GraphicsUnit.Pixel

    ' Draw image to screen.
    g.DrawImage(newImage, destRect, srcRect, units)


End Sub

1 个答案:

答案 0 :(得分:2)

你的标题是" Picturebox"但那里根本没有PictureBox。如果您想在Image中显示PictureBox,请将Image对象分配给Image的{​​{1}}属性。

不要使用GDI +在PictureBox上绘制它,如果您使用GDI +绘制,从不调用Panel。始终在其CreateGraphics事件处理程序中绘制控件。绘图消失的原因是每次Paint事件都会删除所有绘图。通过在Paint事件处理程序中进行绘制,可以确保每次都恢复它。

如果要在显示图像之前修改图像,那么您应该创建一个新的Paint对象,使用GDI +将修改后的图像绘制到该对象上,然后将其分配给Bitmap属性Image的例子,例如

PictureBox