【发布时间】:2013-04-20 21:15:25
【问题描述】:
我想在运行时更改 Background 属性,我必须为其设置 ImageBrush。 我在我的项目中添加了一些图像作为资源,现在我可以将它们用作 System.Drawing.Bitmap。
如何将 System.Drawing.Bitmap 转换为 ImageBrush ?
【问题讨论】:
-
您是在使用数据绑定(可能与 MVVM 一起使用)还是要将其附加到代码隐藏中?
我想在运行时更改 Background 属性,我必须为其设置 ImageBrush。 我在我的项目中添加了一些图像作为资源,现在我可以将它们用作 System.Drawing.Bitmap。
如何将 System.Drawing.Bitmap 转换为 ImageBrush ?
【问题讨论】:
如果您使用代码隐藏来设置它,您可以这样做:
BitmapImage img;
// get bitmapimage from resources and assign to img
ImageBrush brush = new ImageBrush();
brush.ImageSource = img;
myControl.Background = brush;
如果您使用数据绑定,则需要实现 ValueConverter
【讨论】:
来自How to create ImageBrush from System.Drawing.Image in WPF?:
var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions()
);
bitmap.Dispose();
var brush = new ImageBrush(bitmapSource);
“但是,此解决方案不会释放句柄的内存。有关如何消除内存泄漏的信息,请参阅WPF CreateBitmapSourceFromHBitmap() memory leak”
【讨论】: