我在ImageBrush
创建Stream
时遇到了困难。以下代码用于使用Rectangle
填充WPF ImageBrush
:
ImageBrush imgBrush = new ImageBrush();
imgBrush.ImageSource = new BitmapImage(new Uri("\\image.png", UriKind.Relative));
Rectangle1.Fill = imgBrush;
我想要做的是拨打WebRequest
并获取Stream
。然后我想用Stream
图像填充我的矩形。这是代码:
ImageBrush imgBrush = new ImageBrush();
WebRequest request = WebRequest.Create(iconurl);
WebResponse response = request.GetResponse();
Stream s = response.GetResponseStream();
imgBrush.ImageSource = new BitmapImage(s); // Here is the problem
Rectangle1.Fill = imgBrush;
问题在于我不知道如何使用imgBrush.ImageSource
设置response.GetResponseStream()
。如何在Stream
中使用ImageBrush
?
答案 0 :(得分:0)
BitmapImage
constructors没有以Stream
作为参数的重载
要使用响应流,您应该使用无参数构造函数并设置StreamSource
属性。
看起来像这样:
// Get the stream for the image
WebRequest request = WebRequest.Create(iconurl);
WebResponse response = request.GetResponse();
Stream s = response.GetResponseStream();
// Load the stream into the image
BitmapImage image = new BitmapImage();
image.StreamSource = s;
// Apply image as source
ImageBrush imgBrush = new ImageBrush();
imgBrush.ImageSource = image;
// Fill the rectangle
Rectangle1.Fill = imgBrush;