wpf bind property to resize bmp in hight dpi
Having to display bitmap images - not vector at several user's dpi settings in a XBAP WPF application, I'd like to setup a dpiFactor global variable at startup, that will be calculated as a percentage of the original bitmSizeap:
i.e. for 120 dpi I want both size of the image to be: newSize = originalSize * (100 - (120 - 96)) / 100 which means multiply by 75% if the dpi i开发者_StackOverflow中文版s 125% of original.
The dpiFactor have to be defined at startup, and then all measurement to be scaled down (or up) when page is launched. How can I express that in XAML perhaps with a bound property?
Maybe you can use a converter that looks like this:
[ValueConversion(typeof(string), typeof(BitmapImage))]
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string imageSource = value as string;
if (imageSource == null)
return DependencyProperty.UnsetValue;
try
{
BitmapImage originalImage = new BitmapImage(new Uri(imageSource));
int originalWidth = originalImage.PixelWidth;
int originalHeight = originalImage.PixelHeight;
double originalDpiX = originalImage.DpiX;
double originalDpiY = originalImage.DpiY;
BitmapImage scaledImage = new BitmapImage();
scaledImage.BeginInit();
scaledImage.DecodePixelWidth = originalWidth; // Place your calculation here,
scaledImage.DecodePixelHeight = originalHeight; // and here.
scaledImage.UriSource = new Uri(imageSource);
scaledImage.EndInit();
scaledImage.Freeze();
return scaledImage;
}
catch
{
}
return new BitmapImage();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
And in xaml this will looks like this:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:test="clr-namespace:Test">
<Window.Resources>
<test:ImageConverter x:Key="imageConverter" />
</Window.Resources>
<Image Source="{Binding SomePath, Converter={StaticResource imageConverter}}" />
</Window>
To get the system's dpi i think you can use this code.
精彩评论