【问题标题】:Render a UserControl to an Image with a different size then the one at which it is displayed?将 UserControl 渲染到与显示它的大小不同的图像?
【发布时间】:2012-03-22 21:17:09
【问题描述】:

我有一个用户控件,它是我的应用程序的一部分,我正在将它呈现为一个图像,但它正在以当前显示的尺寸呈现。我想要的是将其渲染为固定尺寸,例如 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 是另一个 Control 的子控件,它决定了我的 UserControl 的大小。

谢谢

【问题讨论】:

    标签: c# wpf-controls render


    【解决方案1】:

    我自己解决了这个问题。您需要做的是将您的 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多