Thursday, December 29, 2011

How to Generate Tile Image from StackPanel

You can make your original live tiles from your application by using StandardTileData.
But, the tile layout is limited. So, you cannot add free format text or object into live tile. The layout format is here














 If you want to add customized layout tile, you need to generate Bitmap Image using BitmapImage and WriteableBitmap and save the image into IsoratedStorage.
Please see the movie. This is from my Memo app. The movie shows that I generate a live tile from StackPanel by clicking Check Button after I change some font styles.





  • Code Sample
I introduce code sample from my Memo app. The code generates a live tile from StackPanel. Please see bellow movie.


- xaml code

The xaml code is very simple. You can change the TextBlock on the StackPanel from code.

 <StackPanel Height="173" x:Name="TilePanel" Width="173" Background="Wheat" >  
   <TextBlock x:Name="tileText" Style="{StaticResource PhoneTextNormalStyle}" HorizontalAlignment="Left" FontSize="20" TextWrapping="Wrap" />  
 </StackPanel>  


- C# code

The steps are here.

1. Create BitmapImage url.
2. Create a bitmapImage to IsolatedStorage.
3. Create a live tile using the created bitmapImage.

public static void GenerateTile(StackPanel background, string colorTitle, TextBlock tileText, string id)
{
    //Create BitmapImage url.
    //BitmapImage url should be "/Shared/ShellContent/" to share images.
    var source = new BitmapImage(new Uri("/Shared/ShellContent/", UriKind.Absolute));
    var tileImage = "/Shared/ShellContent/" + colorTitle + id + ".jpg";
    var isoStoreTileImage = string.Format("isostore:{0}", tileImage);

    //Create a bitmapImage to IsolatedStorage.
    using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        //Tile image's Height * Width are 173 * 173.
        var bitmap = new WriteableBitmap(173, 173);

        //Render a bitmap from StackPanel.
        bitmap.Render(background, new TranslateTransform());
        var stream = store.CreateFile(tileImage);
        bitmap.Invalidate();
        bitmap.SaveJpeg(stream, 173, 173, 0, 100);
        stream.Close();
    }

    //Create a live tile using the created bitmapImage.
    StandardTileData secondaryTile = new StandardTileData
    {
        BackgroundImage = new Uri(isoStoreTileImage, UriKind.Absolute),
        Title = "",
        Count = null,
    };
    //Live tile has own url.
    //You can go to your application page when you click a live tile.
    ShellTile.Create(new Uri("/Memo.xaml?id=" + id, UriKind.Relative), secondaryTile);
}


  • Reference
I questioned the topic in StackOverflow. The page is here.
A expert, his name is Claus Jørgensen, gave me excellent solution to resolve the issue. His solution is here.
He also has his code in Guthub.

No comments:

Post a Comment