Windows Phone 8.0 動態磚之Render方式

摘要:Windows Phone 8.0 動態磚之Render方式

很多在開發Windows Phone APP的時候都希望動態磚(Tile)能夠更加的客製化!然而在WP SDK也是可以的! 以下面的Code來看看吧

標準的動態磚產生Code如下

var STile = new StandardTileData();
STile.Title = "Sample Title";
STile.BackTitle = "Sample BTitle";
STile.Count = 1;
STile.BackContent = "Back Content";
STile.BackgroundImage = new Uri("Assets/ApplicationIcon.png", UriKind.Relative);
STile.BackBackgroundImage = new Uri("Assets/ApplicationIcon.png", UriKind.Relative);

ShellTile.ActiveTiles.FirstOrDefault().Update(STile);

上面這行是將做好的StandardTile更新到該APP的動態磚(不論有無釘選到開始上,需要用到System.Linq的Namespace)
ShellTile.Create(new Uri("/MainPage.xaml?TilteID" + Guid.NewGuid().ToString(), UriKind.Relative), STile);

這行則是建立Secondary Tile的方式 在ShellTile.ActiveTiles 裡面除了FirstDefault() 和 First() 以外都是Secondary Tile 且在uri裡面加上TitleID這個是能夠標示選取到哪個Secondary Tile的方式!重複的TileID不會建立Secondary Tile

 

 

 接著,要說明如何將UIElement Render並更新動態磚到Tile

var fileName = string.Format("{0}.png", Guid.NewGuid());
var wbimg = new WriteableBitmap(336, 336);
var tb = new TextBlock();
tb.Text = "123456789";
tb.TextWrapping = TextWrapping.Wrap;
tb.Width = tb.Height = 336;
tb.Foreground = new SolidColorBrush(Colors.White);
tb.FontSize = 82;
tb.Style = Resources["PhoneTextTitle2Style"] as Style;
wbimg.Render(tb, new TranslateTransform());
wbimg.Invalidate();
var contentFolder = await StorageFolder.GetFolderFromPathAsync(Path.Combine(ApplicationData.Current.LocalFolder.Path, "Shared\\ShellContent"));
var targetData = await contentFolder.CreateFileAsync(fileName);
using (var appStream = await targetData.OpenStreamForWriteAsync())
{
  wbimg.SaveJpeg(appStream, 336, 336, 0, 100);
}
var txstile = new StandardTileData();
txstile.Title = "tile";
txstile.BackgroundImage = new Uri(string.Format("isostore:/Shared/ShellContent/{0}", fileName), UriKind.Absolute);
ShellTile.Create(new Uri("/MainPage.xaml?TilteID" + Guid.NewGuid().ToString(), UriKind.Relative), txstile);

這個作法是先建立一個WritableBitmap並給上pixal,這點要注意!Render上去的時候Pixal會和你的UIElement的Width Height產生很大的變化。如上面的Code所示Pixal的大小月大需要放在內部的TextBlock的FontSize也要越大,然後wbimg.Render這個Method要注意的事是需要Render後座Invalidate()這個Method去重新繪製WritableBitmap。接著很簡單的使用Windows.Storage API 來將Render好的wbimg儲存至Shared\ShellConten\這個資料夾!