gpt4 book ai didi

c# - WPF 图像作为工具提示 - DPI 问题

转载 作者:行者123 更新时间:2023-11-30 12:56:36 25 4
gpt4 key购买 nike

我一直在为这个问题挠头。

在我的 MainWindow 上,我有一个 Image,它的 ToolTip 应该以实际大小(或者高度不大于 MainWindow 本身)弹出图像:

<Image x:Name="ss1" Grid.Column="0" Grid.Row="0" Margin="0">
<Image.ToolTip>
<ToolTip DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}">
<Border BorderBrush="Black" BorderThickness="1" Margin="5,7,5,5">
<Image Source="{Binding Source}" MaxHeight="{Binding ElementName=MW,Path=Height}" Stretch="Uniform" ToolTipService.Placement="Top"/>
</Border>
</ToolTip>
</Image.ToolTip>
</Image>

(主窗口的 x:name 是 'MW')

在其他地方的另一个类中,我将 BitmapImage 加载到此图像控件中:

Image img = (Image)mw.FindName("ss1");
img.Source = GetBitmapImageFromDisk(path, UriKind.Absolute);

和 GetBitMapImageFromDisk 方法:

public static BitmapImage GetBitmapImageFromDisk(string path, UriKind urikind)
{
if (!File.Exists(path))
return null;
try
{
BitmapImage b = new BitmapImage(new Uri(path, urikind));
return b;
}
catch (System.NotSupportedException ex)
{
BitmapImage c = new BitmapImage();
return c;
}
}

图像工具提示在鼠标悬停时弹出,但问题是图像的大小似乎取决于图像本身的 DPI。因此,如果由于某种原因它以 DPI 为“762”的图像为目标,则工具提示图像在显示时会非常小。

任何人都可以建议一种用我当前的代码缓解这种情况的方法吗?在运行时加载的图像几乎可以是任何大小、DPI 和纵横比。

最佳答案

非常感谢 Clemens 提供的链接,它确实很有帮助(特别是 pixelwidth 和 pixelheight 属性)。

我在 xaml 中定义最大值时遇到了一些问题,所以最后我将逻辑抽象到后面的代码中。

完整性代码:

XAML:

<Image x:Name="ss1" Grid.Column="0" Grid.Row="0" Margin="0">
<Image.ToolTip>
<ToolTip DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}">
<Border BorderBrush="Black" BorderThickness="1" Margin="5,7,5,5">
<Image Source="{Binding Source}" Stretch="Uniform" ToolTipService.Placement="Top"/>
</Border>
</ToolTip>
</Image.ToolTip>
</Image>

其他类:

Image img = (Image)mw.FindName("ss1");
SetImage(img, path, UriKind.Absolute);

方法:

public static void SetImage(Image img, string path, UriKind urikind)
{
if (!File.Exists(path))
return;
try
{
// load content into the image
BitmapImage b = new BitmapImage(new Uri(path, urikind));
img.Source = b;

// get actual pixel dimensions of image
double pixelWidth = (img.Source as BitmapSource).PixelWidth;
double pixelHeight = (img.Source as BitmapSource).PixelHeight;

// get dimensions of main window
MainWindow mw = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
double windowWidth = mw.ActualWidth;
double windowHeight = mw.ActualHeight;

// set max dimensions on Image.ToolTip
ToolTip tt = (ToolTip)img.ToolTip;
tt.MaxHeight = windowHeight / 1.1;
tt.MaxWidth = windowWidth / 1.1;
img.ToolTip = tt;
}

catch (System.NotSupportedException ex)
{
img.Source = new BitmapImage();
}
}

一旦我可以识别图像的像素宽度和高度,就可以非常简单地在工具提示本身上设置 MaxHeight 和 MaxWidth。

关于c# - WPF 图像作为工具提示 - DPI 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40398095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com