DrawingContext.PushOpacityMask() 与 BitmapImage 不工作

DrawingContext.PushOpacityMask() with BitmapImage does not work

我想获取给定的 BitmapImage 并将其 grayscale/black-and-white 表示用作 DrawingContext 上的不透明蒙版。

我已经完成了颜色转换,所以我得到了演示应用程序的以下状态:

ViewModel 上的方法:

public void Demo()
    {
        var width = 400;
        var height = 400;

        var target = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
        var target2 = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);

        var drawingVisual = new DrawingVisual();
        var drawingVisual2 = new DrawingVisual();

        using (var drawingContext = drawingVisual.RenderOpen())
        {
            var bitmapImage = new BitmapImage(new Uri(@"pack://application:,,,/WarningFilled.png"));

            using (var drawingContext2 = drawingVisual2.RenderOpen())
            {
                drawingContext2.DrawImage(bitmapImage, new Rect(0, 0, width, height));
            }

            target2.Render(drawingVisual2);

            var mask = target2.ToGrayscale();
            this.Mask = mask;

            drawingContext.PushOpacityMask(new ImageBrush(mask));
            drawingContext.DrawRectangle(Brushes.Red, null, new Rect(0, 0, width, height));
            // drawingContext.Pop();
        }

        target.Render(drawingVisual);

        this.Rendered = target;
    }

查看:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wpfApplication1="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <wpfApplication1:MainViewModel></wpfApplication1:MainViewModel>
</Window.DataContext>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Border Grid.Column="0" BorderThickness="2" BorderBrush="Blue" HorizontalAlignment="Center">
        <Image Source="{Binding Rendered}" Width="400" Height="400"></Image>
    </Border>
    <Border Grid.Column="1" BorderThickness="2" BorderBrush="Green" HorizontalAlignment="Center">
        <Image Source="{Binding Mask}" Width="400" Height="400"></Image>
    </Border>
</Grid>

运行 演示应用程序生成以下内容:

我希望左边的红色矩形反映在绘制实际矩形之前推到 DrawingContext 上的不透明蒙版。

您在右侧看到的图像是颜色转换后的 BitmapImage,就在它作为不透明蒙版推送之前。正如我之前提到的,我也尝试过 black/white 转换,但即使只有两种颜色也没有效果。

我已经尝试过很多类似的设置和场景,但我没有让不透明蒙版起作用。

来自 MSDN 上的 Opacity Masks Overview 文章(强调我的):

To create an opacity mask, you apply a Brush to the OpacityMask property of an element or Visual. The brush is mapped to the element or visual, and the opacity value of each brush pixel is used to determine the resulting opacity of each corresponding pixel of the element or visual.

忽略像素的颜色值。