用图像填充 WPF 矩形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15097742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fill WPF rectangle with Image
提问by user1806687
I created new WPF control, added a Rectangle to it, and everyhing works alright, its drawn like it should be. But I just cant paint the rectangle with an actual Image.
我创建了新的 WPF 控件,向它添加了一个 Rectangle,一切正常,它的绘制方式应该是这样。但我不能用实际图像绘制矩形。
BitmapImage bi = GetImage();
ImageBrush imgBrush= new ImageBrush(bi);
this.rectangle.Fill = imgBrush;
But this code just makes the rectangle transparent, except the stroke.
但是这段代码只是使矩形透明,除了笔划。
This is the GetImage()method:
这是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;
textureis an Texture2Dclass, that is made before this code.
texture是一个Texture2D类,在此代码之前制作。
If I return Bitmapinsted of BitmapImagehere and then save that Bitmapthe picture is drawn correctly.
如果我Bitmap在BitmapImage这里返回insted然后保存Bitmap图片绘制正确。
Thank you for your help
感谢您的帮助
回答by user1806687
This is the correct way to convert Bitmap to BitmapImage:
这是正确的转换方式 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();
}
Thanks to "Pawel Lesnikowski", he posted the anwser in the following topic:
感谢“Pawel Lesnikowski”,他在以下主题中发布了答案:

