如何在 WPF 中以彩色呈现单色位图?
回到 Win32 时代,如果我有一个单色位图(实际上它只是一个位图掩码),我可以将该位图渲染到 DeviceContext 上。会发生的情况是,每个有“0”的像素都会渲染为透明,而每个有“1”的像素都会以当前选定的前景色渲染。这非常方便。
然而,经过几周的搜索,我在 WPF 中没有看到类似的东西。
现在我正要推出我自己的 MonochromeBitmapImage 类,但我想如果有人知道另一种方法来做到这一点,那就是你们所有人,SO 用户,所以我的问题是......在 WPF 中,我如何渲染一个单色位图,其中一个值是特定颜色,另一个值是透明的?
Back in Win32 days, if I had a monochromatic bitmap, which is for all intents and purposes just a bitmap mask, I could render that bitmap onto a DeviceContext. What would happen is every pixel where there was a '0' it rendered as transparent, and every pixel where there was a '1' it rendered in the currently selected forecolor. This was very handy.
However, after a few weeks of searching, I haven't seen anything similar in WPF.
Now I was about to just roll my own MonochromeBitmapImage class, but thought if anyone would know another way to do this, it would be you all, the S.O. users, so there's my question... how, in WPF, can I render a monochrome bitmap with one value being a specificed color and the other value being transparent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个非常相似的功能是
UIElement
的OpacityMask
。它将显示 OpacityMask 中不透明的部分。 一起使用SolidColorBrush
等VisualBrush
ImageBrush
这是一个带有
Button
的示例> 使用ImageBrush
A pretty similar feature is
OpacityMask
forUIElement
. It will display the parts that isn't transparent in the OpacityMask. It can be used withSolidColorBrush
etcVisualBrush
ImageBrush
Here is an example with a
Button
using anImageBrush
这取决于您是否需要使用单色位图或者您只是希望能够对图像重新着色。如果您可以使用任何图像格式,我会使用带有 alpha 的 png,那么您可以使用该图像作为 OpacityMask,无需任何代码。通过使用图像作为 OpacityMask,您可以轻松更改颜色、使用渐变或 ImageBrush。
如果您需要使用 1 位位图,使用自定义调色板将它们转换为索引格式非常简单。您可以在调色板中设置所需的颜色,也可以选择任何颜色并将其用作不透明蒙版。 FormatConvertedBitmap 似乎需要不同的格式,只是不同的调色板没有效果。
另一种选择是 PixelShader,对于这种事情来说有点大材小用,但对于更复杂的操作它们很有用。
It depends if you need to use monochrome bitmaps or you just want to be able to recolor the image. If you can use any image format I would use png with alpha then you can use the image as an OpacityMask, no code necessary. By using the image as an OpacityMask you can easily change the colour, use a gradient or an ImageBrush.
If you need to use 1-bit bitmaps it's quite simple to convert them to an indexed format with a custom palette. You could set the colour you want in the palette or just choose anything and use it as an OpacityMask. FormatConvertedBitmap seems to need a different format just a different palette had no effect.
Another option would be a PixelShader it's a bit overkill for this kind of thing but for more complex manipulations they useful.