Any way to save an UIElement created programmatically in an image file?

我的未来我决定 提交于 2019-12-01 10:59:20

It is not working only with elements created in XAML but with these that (as MSDN says) are in VisualTree:

Renders a snapshot of a UIElement visual tree to an image source.

So your method will work if you add your elements for example to your current Page:

LayoutRoot.Children.Add(canvas);

Your UIElemet Height and Width values will be 0 when you create them using code. If you want the image in a particular resolution, try to assign the same height and width to the UIElement as well. The code shown below worked well for me.

    public static void SaveElementAsJPG(FrameworkElement element, string ImageName)
    {
        WriteableBitmap wBitmap = new WriteableBitmap(element, null);
        using (MemoryStream stream = new MemoryStream())
        {
            wBitmap.SaveJpeg(stream, (int)element.ActualWidth, (int)element.ActualHeight, 0, 100);
            wBitmap = null;
            //Use can either save the file to isolated storage or media library.
            //Creates file in Isolated Storage.
            using (var local = new IsolatedStorageFileStream(ImageName, FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication()))
            {
                local.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
            }
            //Creates file in Media Library.
            var lib = new MediaLibrary();
            var picture = lib.SavePicture(ImageName, stream.GetBuffer());
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!