如何在WPF中从System.Drawing.Image创建ImageBrush?

时间:2011-12-13 14:11:09

标签: c# wpf image

我在System.Drawing.Image对象中有图像,我需要从中创建一个ImageBrush对象(例如用于WPF中的Rectangle的Fill属性)。我想应该有办法做到这一点,但我找不到一个。

2 个答案:

答案 0 :(得分:14)

      var image = System.Drawing.Image.FromFile("..."); // or wherever it comes from
      var bitmap = new System.Drawing.Bitmap(image);
      var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(),
                                                                            IntPtr.Zero,
                                                                            Int32Rect.Empty,
                                                                            BitmapSizeOptions.FromEmptyOptions()
            );
      bitmap.Dispose();
      var brush = new ImageBrush(bitmapSource);          
然而,这个解决方案并没有释放句柄的内存。有关如何消除内存泄漏的信息,请参阅WPF CreateBitmapSourceFromHBitmap() memory leak

答案 1 :(得分:2)

<Rectangle  x:Name="RectangleName"                       
                StrokeThickness="1" 
                HorizontalAlignment="Stretch" 
                VerticalAlignment="Stretch" 
                Width="200"
                Height="300"
                Stroke="Black" >
        <Rectangle.Fill>

                <ImageBrush ImageSource="{Binding SelectedComponentsImage}"  x:Name="ComponentVisualBrush" ViewboxUnits="Absolute" 
                Viewbox="0,0,300,300" ViewportUnits="RelativeToBoundingBox" Stretch="UniformToFill" Viewport="0,0,1,1" 
                RenderOptions.EdgeMode="Aliased"  />

        </Rectangle.Fill>
</Rectangle>

这是使用viewmodel Binding。您可以使用图像uri替换Binding。