How to properly use Image as ToolTip?

2019-08-04 14:24发布

问题:

I have a BitmapSource 1690x214 (taken from an EMF file using this code), and I want to use this image as ToolTip. This is the image displayed using Paint:

So i wrote this code:

BitmapSource bmp = myBitmapSource; // "Dk01Light.EMF"

Image img = new Image()
{
    Source = bmp,
    Width = bmp.Width,
    Height = bmp.Height,
    Stretch = Stretch.Uniform,
};

myTooltip = img;

And this is the result:

As you can see, the right and bottom margin are completly different. Why? How can i fix this problem?

回答1:

It seems like a DPI issue. First try removing the Width and Height from your Image initializer. It should also-size to fit its content.

You can also try replacing the code you linked to with the following to make sure the image is being produced properly:

using (System.Drawing.Imaging.Metafile emf = new System.Drawing.Imaging.Metafile(path))
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(emf.Width, emf.Height))
{
    bmp.SetResolution(emf.HorizontalResolution, emf.VerticalResolution);

    using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
    {
        g.DrawImage(emf,
            new Rectangle(0, 0, emf.Width, emf.Height),
            new Rectangle(0, 0, emf.Width, emf.Height),
            GraphicsUnit.Pixel
        );

        return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
    }
}