C# 将UserControl渲染为与显示它的图像大小不同的图像?

C# 将UserControl渲染为与显示它的图像大小不同的图像?,c#,wpf-controls,render,C#,Wpf Controls,Render,我有一个UserControl,它是我的应用程序的一部分,我正在将它渲染为一个图像,但它正在以当前显示的维度进行渲染。我想要的是将其渲染为固定尺寸(比如500x500),但不使用新尺寸向用户渲染 UserControl temp = pane.Content; RadBitmap radImage = new RadBitmap(temp); // Renders UserControl to Image PngFormatProvider provider = new PngFormatPro

我有一个UserControl,它是我的应用程序的一部分,我正在将它渲染为一个图像,但它正在以当前显示的维度进行渲染。我想要的是将其渲染为固定尺寸(比如500x500),但不使用新尺寸向用户渲染

UserControl temp = pane.Content;
RadBitmap radImage = new RadBitmap(temp); // Renders UserControl to Image
PngFormatProvider provider = new PngFormatProvider();

return provider.Export(radImage); // returns the Image as a png encoded Byte Array
注意:我的UserControl是另一个控件的子控件,该控件指定我的UserControl的大小


谢谢

我自己解决了这个问题。您需要做的是按照您希望图片的尺寸调整UserControl的VisualParent,将UserControl渲染为图像,并将VisualParent的大小恢复为原来的大小

        UserControl userControl = pane.Content;
        ContentPresenter visualParent = (VisualTreeHelper.GetParent(userControl) as ContentPresenter);

        double oldWidth = visualParent.Width;
        double oldHeight = visualParent.Height;

        visualParent.Width = BitmapImageWidth;
        visualParent.Height = BitmapImageHeight;
        visualParent.UpdateLayout(); // This is required! To apply the change in Width and Height

        WriteableBitmap bmp = new WriteableBitmap(BitmapImageWidth, BitmapImageHeight);
        bmp.Render(userControl, null);
        bmp.Invalidate(); // Only once you Invalidate is the Control actually rendered to the bmp
        RadBitmap radImage = new RadBitmap(bmp);

        visualParent.Width = oldWidth; // Revert back to original size
        visualParent.Height = oldHeight; // Revert back to original size

        return new PngFormatProvider().Export(radImage); // returns the Image as a png encoded Byte Array