Silverlight 4 - Render UIElement as an Image

寵の児 提交于 2019-12-01 15:43:27
Bruno

Assuming the FrameworkElement you want to render is named elementToRender and the Image where you want to place the rendered output is called image, use the following code on your button's click handler:

var writeableBitmap = new WriteableBitmap((int)elementToRender.RenderSize.Width, (int)elementToRender.RenderSize.Height);

writeableBitmap.Render(elementToRender, new ScaleTransform() { ScaleX = 1, ScaleY = 1 });
writeableBitmap.Invalidate();

image.Source = writeableBitmap;
MyKuLLSKI

You can also do the following:

private void SetImageSourceBasedOnElement(Image image, UIElement element)
{
    if (element != null)
    {
        WriteableBitmap writableBitmap = new WriteableBitmap(element, null);
        writableBitmap.Invalidate();

        image.Source = writableBitmap;
     }
 }
WriteableBitmap wb = new WriteableBitmap(UIElement, new ScaleTransform() { ScaleX = 1, ScaleY = 1 });
wb.Invalidate();
Image.Source = wb;
Zenexer

Ultimately, no, you cannot render an entire UIElement, including the parts that aren't visible due to scrolling overflow, etc.

I looked into how you could get around this using reflection. Unfortunately, you cannot override how UIElement renders, as it is just a light wrapper for the internal class XcpImports, which in turn is a wrapper for various native methods used throughout Silverlight. In other words, UIElement and how it is rendered is completely native, and thus there is no (easy) way to override how it displays using reflection.

If you wanted to take the hackish approach, you could enclose your element in a Grid, remove it from that grid, put it in another grid that is the same size as the element--see where I'm going with this? But that would be quite a hassle, and hackish at best.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!