3

我被卡住了如何 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;
4

2 回答 2

4

您可以ImageBrush从以下位置创建BitmapSource

    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;
    }
于 2012-05-17T14:18:57.113 回答
0

例子:

System.Drawing.Bitmap flag = new System.Drawing.Bitmap(10, 10);
for( int x = 0; x <  flag.Height; ++x )
    for( int y = 0; y < flag.Width; ++y )
        flag.SetPixel(x, y, Color.Black);
for( int x = 0; x < flag.Height; ++x )
    flag.SetPixel(x, x, Color.Black);

和转换:

private BitmapImage Bitmap2BitmapImage(Bitmap bitmap) 
{ 
    using (MemoryStream ms = new MemoryStream()) 
    { 
        bitmap.Save(ms, ImageFormat.Png); 
        ms.Position = 0; 
        BitmapImage bi = new BitmapImage(); 
        bi.BeginInit(); 
        bi.StreamSource = ms; 
        bi.EndInit(); 

        return bi; 
    } 
} 
于 2012-05-17T14:15:18.963 回答