Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIElement to image file (WP7)

I have a StackPanel which includes a few Rectangles that I want put to an image file (e.g. PNG). I'm developing this on Windows Phone 7 and most of the information I found on the internet wasn't applicable (I think) to WP7.

I think the System.Windows.Media.Imaging namespace is the key to this, but I'm not sure where to begin.

This is basically what I want to do:

StackPanel stack = new StackPanel();
List<Rectangle> recList = new List<Rectangle>();

add some rectangles to recList

foreach(var x in recList)
     stack.Children.Add(x);

then save the stackpanel to an image file...

like image 859
judehall Avatar asked Jun 09 '11 22:06

judehall


1 Answers

You can use a WriteableBitmap to save the image.

WriteableBitmap wb = new WriteableBitmap(stack, null);
MemoryStream ms = new MemoryStream();

wb.SaveJpeg(ms, myWidth, myHeight, 0, 100);

You can change the MemoryStream to be an Isolated Storage stream instead. If you want to display the above MemoryStream in an Image control:

 BitmapImage bmp = new BitmapImage();
 bmp.SetSource(ms);
 image1.Source = bmp;

Or, saving to Isolated Storage:

using (var isoFileStream = new IsolatedStorageFileStream("myPicture.jpg", FileMode.OpenOrCreate, IsolatedStorageFile.GetUserStoreForApplication())) 
{                     
    wb.SaveJpeg(isoFileStream, myWidth, myHeight, 0, 100);                    
}
like image 143
keyboardP Avatar answered Oct 13 '22 20:10

keyboardP