假设我有一个名为“GridA”的网格
我搜索过的所有地方都表明我使用
GridA.DrawToBitmap
但是网格没有那种方法..
然后我变得狡猾,将它包裹在一个堆栈面板中并称为“stackpanel1”
面板也没有这种方法。
那么我应该如何将我的网格保存为 wpf 中的图像?
您可以将任何绘图视觉对象转换为位图。这是我用来从 WPF 绘制的控件添加图标覆盖、将其添加到 UserControl 或重构它的一些代码。有关完整示例,请参见http://alski.net/post/2012/01/11/WPF-Icon-Overlays.aspx
protected void InitializeBitmapGeneration()
{
LayoutUpdated += (sender, e) => _UpdateImageSource();
}
public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register(
"ImageSource",
typeof(ImageSource),
typeof(CountControl),
new PropertyMetadata(null));
/// <summary>
/// Gets or sets the ImageSource property. This dependency property
/// indicates ....
/// </summary>
public ImageSource ImageSource
{
get { return (ImageSource)GetValue(ImageSourceProperty); }
set { SetValue(ImageSourceProperty, value); }
}
private void _UpdateImageSource()
{
if (ActualWidth == 0 || ActualHeight == 0)
{
return;
}
ImageSource = GenerateBitmapSource(this, 16, 16);
}
public static BitmapSource GenerateBitmapSource(ImageSource img)
{
return GenerateBitmapSource(img, img.Width, img.Height);
}
public static BitmapSource GenerateBitmapSource(ImageSource img, double renderWidth, double renderHeight)
{
var dv = new DrawingVisual();
using (DrawingContext dc = dv.RenderOpen())
{
dc.DrawImage(img, new Rect(0, 0, renderWidth, renderHeight));
}
var bmp = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32);
bmp.Render(dv);
return bmp;
}
public static BitmapSource GenerateBitmapSource(Visual visual, double renderWidth, double renderHeight)
{
var bmp = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32);
var dv = new DrawingVisual();
using (DrawingContext dc = dv.RenderOpen())
{
dc.DrawRectangle(new VisualBrush(visual), null, new Rect(0, 0, renderWidth, renderHeight));
}
bmp.Render(dv);
return bmp;
}
}