Search code examples
c#windows-phone-7live-tile

Dynamic LiveTile - adding background image?


Working wth live tiles in my Windows Phone 7 app and it's working quite okay.

I'm now trying to create a dynamic live tile and I can't get the background image to show up. When using the code below I only get a black tile. The text I add is shown but not the background image. Image "Build action" is set to "Content".

Any ideas?

StackPanel sp = new StackPanel();
sp.Height = 173;
sp.Width = 173;

string fileName = "tile.jpg";
BitmapImage image = new BitmapImage(new Uri(fileName, UriKind.Relative));
ImageBrush brush = new ImageBrush();
brush.ImageSource = image;
sp.Background = brush;

sp.Measure(new Size(173, 173));
sp.Arrange(new Rect(0, 0, 173, 173));
sp.UpdateLayout();
WriteableBitmap wbm = new WriteableBitmap(173, 173);
wbm.Render(sp, null);
wbm.Invalidate();

Solution

  • I also had problems using BitmapImage and still don't know how to solve it. But I found a workaround using WriteableBitmap:

            // grid is container for image and text
            Grid grid = new Grid();
    
            // load your image
            StreamResourceInfo info = Application.GetResourceStream(new Uri(filename, UriKind.Relative));
            // create source bitmap for Image control (image is assumed to be alread 173x173)
            WriteableBitmap wbmp2 = new WriteableBitmap(1,1);
            wbmp2.SetSource(info.Stream);
            Image img = new Image();
            img.Source = wbmp2;
            // add Image to Grid
            grid.Children.Add(img);
    
            TextBlock text = new TextBlock() { FontSize = (double)Resources["PhoneFontSizeExtraLarge"], Foreground = new SolidColorBrush(Colors.White) };
            // your text goes here:
            text.Text = "Hello\nWorld";
            grid.Children.Add(text);
    
            // this is our final image containing custom text and image
            WriteableBitmap wbmp = new WriteableBitmap(173, 173);
    
            // now render everything - this image can be used as background for tile
            wbmp.Render(grid, null);
            wbmp.Invalidate();