简体   繁体   中英

Create BitmapImage and apply to it a specific Color

I got stuck how to create BitmapImage based on some color value ?

For example I have string " Black " so I need black BitmapImage .

How it could be done?

Thank you!

-- UPDATES (I put this code for @StephenChung )

The idea is to do Grid with any opacity and don't apply opacity to its children. So I create an image by ANY color I need and apply opacity for it.

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;

You can create ImageBrush from 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;
    }

Example:

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

and the conversion:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM