C# 如何正确使用图像作为工具提示?
我有一个C# 如何正确使用图像作为工具提示?,c#,wpf,image,tooltip,bitmapsource,C#,Wpf,Image,Tooltip,Bitmapsource,我有一个BitmapSource1690x214(使用代码从EMF文件中获取),我想将此图像用作工具提示。这是使用Paint显示的图像: 所以我写了这段代码: BitmapSource bmp = myBitmapSource; // "Dk01Light.EMF" Image img = new Image() { Source = bmp, Width = bmp.Width, Height = bmp.Height, Stretch = Stretch.
BitmapSource
1690x214(使用代码从EMF文件中获取),我想将此图像用作工具提示。这是使用Paint显示的图像:
所以我写了这段代码:
BitmapSource bmp = myBitmapSource; // "Dk01Light.EMF"
Image img = new Image()
{
Source = bmp,
Width = bmp.Width,
Height = bmp.Height,
Stretch = Stretch.Uniform,
};
myTooltip = img;
这就是结果:
正如您所看到的,右边距和底边距完全不同。为什么?如何解决此问题?这似乎是一个DPI问题。首先尝试从图像初始值设定项中删除宽度和高度。它的大小也应该适合它的内容
您还可以尝试用以下代码替换链接到的代码,以确保正确生成图像:
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());
}
}
我只添加了bmp.SetResolution(emf.HorizontalResolution,emf.VerticalResolution)代码>并且它工作!