C# 带alpha的FormatConvertedBitmap
我的WPF有问题。我正在制作一个带有图像的删除按钮。但是,当按钮被禁用时,我希望显示灰度图像 我找到了,但我不想在我的程序中添加整个类。相反,我试图以这种方式模仿这种行为:C# 带alpha的FormatConvertedBitmap,c#,wpf,xaml,C#,Wpf,Xaml,我的WPF有问题。我正在制作一个带有图像的删除按钮。但是,当按钮被禁用时,我希望显示灰度图像 我找到了,但我不想在我的程序中添加整个类。相反,我试图以这种方式模仿这种行为: BitmapImage img_Delete = new System.Windows.Media.Imaging.BitmapImage(new Uri("the png URI", UriKind.RelativeOrAbsolute)); ImageSource img_DeleteDisabled = null;
BitmapImage img_Delete = new System.Windows.Media.Imaging.BitmapImage(new Uri("the png URI", UriKind.RelativeOrAbsolute));
ImageSource img_DeleteDisabled = null;
[...]
Button btDel = new Button() { Width = 20, Height = 20, ToolTip = "Delete", Margin = new Thickness(5), HorizontalAlignment = System.Windows.HorizontalAlignment.Right };
btDel.IsEnabled = isdeletable(obj);
if (!btDel.IsEnabled && (img_DeleteDisabled == null))
{
img_DeleteDisabled = new FormatConvertedBitmap(img_Delete, PixelFormats.Gray32Float, null, 0);
}
btDel.Content = (new System.Windows.Controls.Image()
{
Width = 16,
Height = 16,
HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
VerticalAlignment = System.Windows.VerticalAlignment.Stretch,
Source = btDel.IsEnabled ? img_Delete : img_DeleteDisabled
});
它以预期的方式运行,除了。。好吧,我给你看:
左侧为启用状态,右侧为禁用状态
正如你所见,阿尔法通道消失了。如何将其重新整合?在这些评论的帮助下,我发现我在考虑应用不透明遮罩的错误位置
OpacityMask
应应用于按钮,而不是图像。这是因为不透明度应用于整个图像,而不是其源
因此,正确的实现方法是
btDel.Content = (new System.Windows.Controls.Image()
{
Width = 16,
Height = 16,
HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
VerticalAlignment = System.Windows.VerticalAlignment.Stretch,
Source = btDel.IsEnabled ? img_Delete : img_DeleteDisabled,
OpacityMask = new ImageBrush(img_Delete)
});
这样,遮罩将应用于按钮图像。结果就是我所需要的:
什么是alpha通道?alpha通道包含透明度信息:在左侧,红十字会有一个透明的背景,而灰色的有一个黑色背景。尝试设置
btDel.background=brusks.transparent
那么您可以在图像
构造函数中设置不透明度掩码
(如设置源
)?@bars222看起来不透明度掩码应该在按钮本身中设置,而不是在图像源中设置。。查看我的答案了解详细信息我很高兴我的建议得到了帮助,并且像Source
那样设置OpacityMask
也得到了帮助,也许我在评论中不清楚(我是用图像构造函数写的,但意思是初始化代码)。@bars222实际上我没有把按钮内容看作图像,所以我想你是说在img\u DeleteDisabled=new Image
构造函数中使用它。。。对不起,没关系,我们终于找到了解决办法。