在 WPF 中为部分透明的图像着色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28247010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:54:04  来源:igfitidea点击:

Tint a partially transparent image in WPF

c#wpfxamlimage-manipulation

提问by Cyral

How can I tint/colorize an image in WPF (using MVVM) without sacrificing performance? A purely XAML solution would be ideal, as modifying bitmaps in the code will cause performance loss with lots of changing images. The image is made up of more than simple shapes, so it is not possible using a path.

如何在不牺牲性能的情况下在 WPF(使用 MVVM)中对图像进行着色/着色?纯粹的 XAML 解决方案将是理想的,因为修改代码中的位图会导致性能损失,因为图像会发生大量变化。图像由多个简单的形状组成,因此无法使用路径。

回答by Cyral

Unlike WinForms/GDI+, WPF does not seem to contain any easy ways to colorize/tint an image as it is being rendered. Two ideas for accomplishing this are, using a shader, or overlaying a colored rectangle over the image.

与 WinForms/GDI+ 不同,WPF 似乎不包含任何简单的方法来为正在渲染的图像着色/着色。实现这一点的两个想法是,使用着色器,或在图像上覆盖一个彩色矩形。

I decided to try the rectangle route and found that it works. Basically, all you need to do is overlay a colored rectangle over your image, and use an OpacityMaskto restrict the color fill to a certain area. OpacityMask is primarily used with paths, but it can take any kind of brush, including an ImageBrush. This means you can use your image as a "stencil" for the colored fill.

我决定尝试矩形路线并发现它有效。基本上,您需要做的就是在图像上覆盖一个彩色矩形,并使用OpacityMask将颜色填充限制在某个区域。OpacityMask 主要用于路径,但它可以使用任何类型的画笔,包括ImageBrush. 这意味着您可以将图像用作彩色填充的“模板”。

Example:(Taken from my application where a user can "highlight" a section of a map, the actual image looks like this)

示例:(取自我的应用程序,用户可以在其中“突出显示”地图的一部分,实际图像如下所示

Before Overlay & Mask

覆盖和遮罩之前

http://i.imgur.com/rdI7LGq.png

http://i.imgur.com/rdI7LGq.png

After Overlay & Mask

叠加和遮罩后

http://i.imgur.com/WkJdmvG.png

http://i.imgur.com/WkJdmvG.png

Here is all of the required XAML for this:

这是为此所需的所有 XAML:

<Image
    Source="{Binding MyImage}"
    Width="150"
    Height="150" />
<Rectangle Width="150" Height="150">
    <Rectangle.Fill>
        <SolidColorBrush Color="{Binding Color}"/>
    </Rectangle.Fill>
    <Rectangle.OpacityMask>
        <ImageBrush ImageSource="{Binding MyImage}"/>
    </Rectangle.OpacityMask>
</Rectangle>

To bind the color to a brush as I did, use a ColorToBrushConverter.

要像我一样将颜色绑定到画笔,请使用ColorToBrushConverter