How do I prevent Graphics.DrawImage from scaling the picture?

时间:2015-07-28 22:44:19

标签: vb.net visual-studio-2013

I am using a code that creates an image tooltip when the user hovers over the button. However, for some reason, for some of the buttons, the image gets scaled larger and doesnt completely fit in the tooltip window. I have no idea why some images are getting scaled and not others. Here is the code:

Protected Overrides Sub OnLoad(e As EventArgs)
    MyBase.OnLoad(e)
    ToolTip1.OwnerDraw = True
    For Each ctrl As Control In Controls
        If TypeOf ctrl Is Button Then
            ToolTip1.SetToolTip(ctrl, " ")
        End If
    Next
End Sub

Private Sub ToolTip1_Popup(sender As Object, e As PopupEventArgs) Handles ToolTip1.Popup
    Dim oTemplate As String = e.AssociatedControl.Name
    Dim ButtonPic As Image = Image.FromFile(System.IO.Path.GetFullPath("TemplatesResources\MouseHoverPics\" & oTemplate & ".png"))
    e.ToolTipSize = New Size(ButtonPic.Size.Width, ButtonPic.Size.Height)
End Sub

Private Sub ToolTip1_Draw(sender As Object, e As DrawToolTipEventArgs) Handles ToolTip1.Draw
    Dim oTemplate As String = e.AssociatedControl.Name
    Dim ButtonPic As Image = Image.FromFile(System.IO.Path.GetFullPath("TemplatesResources\MouseHoverPics\" & oTemplate & ".png"))
    e.Graphics.Clear(SystemColors.Info)
    e.Graphics.DrawImage(ButtonPic, New System.Drawing.Point(0, 0))
End Sub

The results:

Looking good at first. Looks good!

Scaling begins.... Uh Oh!

Even more scaling the further right I go... could it possibly have to do with the button placement? I cant see why the code would take that into consideration What...

Any help would be appreciated.

1 个答案:

答案 0 :(得分:1)

这是因为当你打电话时

  • e.ToolTipSize =新尺寸(ButtonPic.Size.Width,ButtonPic.Size.Height)

设置[弹出窗口的大小=图像的大小]。但是,如果你的鼠标光标与窗口边界之间没有足够的空间,会发生什么?弹出窗口自身调整大小,当您在其中加载图像时,图像缩放自身以匹配当前宽度/高度

  • e.Bounds()

所以你要做的就是在调用DrawImage()方法之前检查弹出窗口的边界并按比例调整比例。

此处和示例

Private Sub ToolTip1_Draw(sender As Object, e As DrawToolTipEventArgs) Handles ToolTip1.Draw
    Dim oTemplate As String = e.AssociatedControl.Name
    Dim ButtonPic As Image = Image.FromFile(System.IO.Path.GetFullPath("TemplatesResources\MouseHoverPics\" & oTemplate & ".png"))
    e.Graphics.Clear(SystemColors.Info)
    If ButtonPic.Width > e.Bounds.Widht Or ButtonPic.Height > e.Bounds.Height Then
        [code to rescale, make it as you prefer]
    End If
    e.Graphics.DrawImage(ButtonPic, New System.Drawing.Point(0, 0))
End Sub