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

本文关键字:Drawing Image 创建 ImageBrush System 中从 WPF | 更新日期: 2023-09-27 18:17:47

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

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

      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 createbitmapsourcefrombitmap()内存泄漏

<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>

这是与视图模型绑定。您可以将Binding替换为图像uri。