Nikolas Jíša
Nikolas Jíša

Reputation: 709

Save a WPF UserControl as a vector image

I have created a WPF UserControl library. And I would like to put a vector picture of each UserControl (in default settings) to documentation. So my question is: How do I create a vector image of a UserControl?

Thanks for any efforts.

Upvotes: 3

Views: 1654

Answers (1)

David
David

Reputation: 16287

Capture a vector image seems difficult, and is you control composed of vector graphics only? If you just wish to get a png or bmp, below code might help:

ImageCapturer.SaveToPng(AnyControl, "Capture.png");

class ImageCapturer
{               
    public static void SaveToBmp(FrameworkElement visual, string fileName)
    {
        var encoder = new BmpBitmapEncoder();
        SaveUsingEncoder(visual, fileName, encoder);
    }

    public static void SaveToPng(FrameworkElement visual, string fileName)
    {
        var encoder = new PngBitmapEncoder();
        SaveUsingEncoder(visual, fileName, encoder);
    }

    private static void SaveUsingEncoder(FrameworkElement visual, 
                 string fileName, BitmapEncoder encoder)
    {
        RenderTargetBitmap bitmap = new RenderTargetBitmap(
               (int)visual.ActualWidth, 
               (int)visual.ActualHeight, 96, 96, PixelFormats.Pbgra32);
        bitmap.Render(visual);
        BitmapFrame frame = BitmapFrame.Create(bitmap);
        encoder.Frames.Add(frame);

        using (var stream = File.Create(fileName))
        {
            encoder.Save(stream);
        }
    }
}

Upvotes: 2

Related Questions