簡體   English   中英

創建BitmapImage並將其應用於特定的顏色

[英]Create BitmapImage and apply to it a specific Color

我遇到了如何基於某些顏色值創建BitmapImage

例如,我有字符串“ 黑色 ”所以我需要黑色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;
    }

例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM