动态LiveTile - 添加背景图像?

时间:2011-11-06 17:28:40

标签: c# windows-phone-7 live-tile

在我的Windows Phone 7应用程序中使用活动磁贴,它工作正常。

我现在正在尝试创建一个动态的实时图块,但我无法显示背景图像。当使用下面的代码时,我只得到一个黑色的瓷砖。我添加的文字显示但不是背景图片。图像“构建操作”设置为“内容”。

有什么想法吗?

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();

3 个答案:

答案 0 :(得分:3)

我在使用BitmapImage时也遇到了问题,但仍然不知道如何解决它。但我找到了使用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();

答案 1 :(得分:2)

试试这个 - 它对我有用:

Uri uri = new Uri("tile.jpg", UriKind.Relative);
StreamResourceInfo sri = Application.GetResourceStream(uri);

WriteableBitmap wbm = new WriteableBitmap(173, 173);
wbm.SetSource(sri.Stream);

using (var stream = IsolatedStorageFile.GetUserStoreForApplication().CreateFile("/Shared/ShellContent/tile.png"))
{
    wbm.SaveJpeg(stream, 173, 173, 0, 100);
}

var data = new StandardTileData();
data.BackgroundImage = new Uri("isostore:/Shared/ShellContent/tile.png", UriKind.Absolute);
data.Title = "updated image";

var tile = ShellTile.ActiveTiles.First();
tile.Update(data);

答案 2 :(得分:0)

我认为问题是图像是异步加载的,因此不可用。 我成功完成了这段代码:

BitmapImage bmi = new BitmapImage();
bmi.CreateOptions = BitmapCreateOptions.None;
StreamResourceInfo streamInfo = 
     Framework.App.GetResourceStream(new Uri(@"images\img.png", 
          UriKind.Relative));
bmi.SetSource(streamInfo.Stream);
imgctl.Source = bmi;

然而,当我从Xaml加载时,我仍然试图让它工作:

<Image  HorizontalAlignment="Center" Width="173" Height="89" x:Name="imgctl" 
    Source="/images/lowsunrise.png"/>

在这种情况下,图像永远不会被加载,并且没有任何事件触发,可能是因为它没有连接到可视树,因此不会被渲染。