c# - 创建 BitmapImage 并为其应用特定的 Color

标签 c# wpf

我不知道如何根据一些颜色值创建BitmapImage

例如我有字符串“Black”所以我需要黑色BitmapImage

如何实现?

谢谢!

-- 更新(我把这段代码用于 @StephenChung)

想法是用任何不透明度来处理 Grid 并且不将不透明度应用于其子项。 所以我用我需要的任何颜色创建图像并为其应用不透明度。

BitmapSource bs = CreateBitmapSource(GetBackgroundColorValue());
// and here I use method of @StaWho CreateBitmapSource()
ImageBrush ib2 = new ImageBrush(bs);
ib2.Opacity = Opacity;
ib2.Stretch = Stretch.Fill;
RootGrid.Background = ib2;

最佳答案

您可以从 BitmapSource 创建 ImageBrush:

    private BitmapSource CreateBitmapSource(System.Windows.Media.Color color)
    {
        int width = 128;
        int height = width;
        int stride = width / 8;
        byte[] pixels = new byte[height * stride];

        List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>();
        colors.Add(color);
        BitmapPalette myPalette = new BitmapPalette(colors);

        BitmapSource image = BitmapSource.Create(
            width,
            height,
            96,
            96,
            PixelFormats.Indexed1,
            myPalette,
            pixels,
            stride);

        return image;
    }

关于c# - 创建 BitmapImage 并为其应用特定的 Color,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10637064/

相关文章:

C# 将字符串复制到字节缓冲区

c# - 不使用拆分功能比较版本号

c# - 从数据库中获取数据 C#

c# - 移动和旋转 map 有问题吗?

c# - 为什么我的字符串格式化程序在此多重绑定(bind)中被忽略?

c# - 如何计算 WPF 绑定(bind)中的值

wpf - (多个)MultiDataTrigger 与转换器的效率

c# - 使用 JsonConvert C# 解析 json 字符串

c# - 如何为子属性在 Style、Setter 和 HierarchicalDataTemplate 上设置 DataContext 绑定(bind)?

c# - 绑定(bind)到 UserControl 的依赖属性