在WPF中为部分透明的图像着色 [英] Tint a partially transparent image in WPF

查看:288
本文介绍了在WPF中为部分透明的图像着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不牺牲性能的情况下(使用MVVM)在WPF中对图像进行着色/着色?纯粹的XAML解决方案将是理想的选择,因为在代码中修改位图会导致性能下降,并且图像变化很多.该图像不仅由简单的形状组成,因此无法使用路径.

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.

推荐答案

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

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.

我决定尝试矩形路由,并发现它可以工作.基本上,您需要做的就是在图像上覆盖一个彩色矩形,并使用

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 OpacityMask to 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.

示例(从我的应用程序中,用户可以突出显示"地图的一部分,实际图像看起来像

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

覆盖前&遮罩

覆盖后&遮罩

这是为此所需的所有XAML:

Here is all of the required XAML for this:

<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>

要将颜色绑定到笔刷,请使用 ColorToBrushConverter .

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

这篇关于在WPF中为部分透明的图像着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆