2

我创建了新的 WPF 控件,向其中添加了一个 Rectangle,一切正常,它的绘制就像它应该的那样。但我不能用实际的图像绘制矩形。

BitmapImage bi = GetImage();
ImageBrush imgBrush= new ImageBrush(bi);

this.rectangle.Fill = imgBrush;

但是这段代码只是使矩形透明,除了笔划。

这是GetImage()方法:

BitmapImage bi;

using (MemoryStream ms = new MemoryStream())
{
    bi = new BitmapImage();
    bi.CacheOption = BitmapCacheOption.OnLoad;

    texture.SaveAsPng(ms, texture.Width, texture.Height);

    ms.Seek(0, SeekOrigin.Begin);

    bi.BeginInit();
    bi.StreamSource = ms;
    bi.EndInit();

    ms.Close();
}
return bi;

texture是一个Texture2D类,在此代码之前生成。

如果我Bitmap在这里返回 instedBitmapImage然后保存Bitmap图片是否正确绘制。

感谢您的帮助

4

1 回答 1

4

这是正确的转换方法Bitmap to BitmapImage:

using(MemoryStream memory = new MemoryStream())
{
    bitmap.Save(memory, ImageFormat.Png);
    memory.Position = 0;
    BitmapImage bitmapImage = new BitmapImage();
    bitmapImage.BeginInit();
    bitmapImage.StreamSource = memory;
    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
    bitmapImage.EndInit();
}

感谢“Pawel Lesnikowski”,他在以下主题中发布了答案:

从 System.Drawing.Bitmap 加载 WPF BitmapImage

于 2013-02-28T18:29:52.583 回答