是否可以将网格转换为图像文件,如位图?

时间:2012-09-19 13:26:23

标签: c# wpf

假设我有一个名为'GridA'的网格

我搜索的每个地方都建议我使用

 GridA.DrawToBitmap

但网格没有这种方法..

然后我变得狡猾并将它包裹在一个堆叠面板中并称为“stackpanel1”

面板也没有这种方法。

那么我该如何将网格保存为wpf中的图像?

1 个答案:

答案 0 :(得分:1)

您可以将任何绘图视觉转换为位图。这里有一些代码用于从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;
    }
}