我很难从Stream
创建我的ImageBrush
。以下代码用于使用ImageBrush
填充WPF Rectangle
:
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;
问题是我不知道如何使用response.GetResponseStream()
设置imgBrush.ImageSource
。如何在ImageBrush
中消耗Stream
?
BitmapImage
构造函数没有超载以 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;