ImageSource上的转换器 - 将图像转换为灰度 [英] Convertor on ImageSource - convert image to grayscale
问题描述
我在Image控件上有多个绑定。我绑定两个属性,一个是bool(IsLogged)类型,一个是typeof Uri(ProfilePhoto)。
I have multibinding on Image control. I bind two properties one is type of bool(IsLogged) and one is typeof Uri (ProfilePhoto).
XAML:
<Image.Source >
<MultiBinding Converter="{StaticResource avatarConverter}">
<Binding Path="ProfilePhoto"></Binding>
<Binding Path="StatusInfo.IsLogged"></Binding>
</MultiBinding>
</Image.Source>
</Image>
我创建转换器,如果属性IsLogged为false,则将BitmapImage转换为灰度。
I create converter, which convert BitmapImage to gray scale if property IsLogged is false.
看起来像这样:
public class AvatarConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var image = values[0] as BitmapImage;
string s = values[1].ToString();
bool isLogged = System.Convert.ToBoolean(s);
if (!isLogged)
{
try
{
if (image != null)
{
var grayBitmapSource = new FormatConvertedBitmap();
grayBitmapSource.BeginInit();
grayBitmapSource.Source = image;
grayBitmapSource.DestinationFormat = PixelFormats.Gray32Float;
grayBitmapSource.EndInit();
return grayBitmapSource;
}
return null;
}
catch (Exception ex)
{
throw ex;
}
}
return image;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
如果只绑定图像源属性,它的效果很好键入BitmapImage,但我需要绑定属性类型的Uri。
It works good if only I bind on image source property type fo BitmapImage, but I need bind property type of Uri.
我担心转换器中的创建变量BitmapImage和源使用Uri。
将此变量作为图像源返回。我认为这不是理想的方式。也许我错了。
I have a fear of the creation variable BitmapImage in converter and as source use Uri. An return this variable as Source of image. I think this is not ideal way. Maybe I am wrong.
你有什么看法
一些优雅的解决方案?
推荐答案
虽然你可以使用转换器,但有一个更好的选择:使用着色器效果。你会在这个上找到GreyscaleEffect的实现。页面。
Although you can do it with a converter, there is a much better option: using a shader effect. You'll find an implementation of a GreyscaleEffect on this page.
<Style x:Key="grayedIfNotLogged" TargetType="Image">
<Style.Triggers>
<DataTrigger Binding="{Binding StatusInfo.IsLogged}" Value="False">
<Setter Property="Effect">
<Setter.Value>
<fx:GrayscaleEffect />
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
...
<Image Source="..." Style="{StaticResource grayedIfNotLogged}" />
这篇关于ImageSource上的转换器 - 将图像转换为灰度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!