Silverlight 與中文顯示

Silverlight 內建9種英文字型, 但是這些內建字型(如下), 都不包含亞洲語系統的字型(中日韓), 使得在網頁裡顯示中文字需要額外下載字型檔。Silverlight 支援的字型檔格式是 TrueType 與 OpenType, 比較麻煩的現在所有中文字型檔, 都是以作業系統為授權對象(不管是微軟內建的字型, 或是其他作業系統提供的字型), 而一些號稱免費的字型(如:教育部標準字型)都不可作為商業用途, 因此字型檔的合法取得是另一個另人頭痛的問題。

Silverlight 並不支援 WPF 裡的 FlowDocument, 因此 Silverlight 顯示文章上有很大的限制, 只能用 TextBlock 顯示文章, 但整個 TextBlock 裡都是同樣的字型, 連大小都不能變化, 因此, Silverlight 還沒辦法取代 HTML 成為網頁文件的表現技術。

TextBlock 有一個 SetFontSource() 的函式, 用來設定字型檔的資源下載者(是 downloader, 而不是字型檔本身), 要先建立一個 downloader, 然後用 downloader 背景下載字型檔(.ttf格式)或是包函了字型檔的資源檔(.zip格式), 下載完成之後, 再把 downloader 用 SetFountSource()  指定給 TextBlock, 接下來要用 FontFamily 指定字型名稱。大致寫法如下:

資源檔準備:

將 Vista 裡的 simhei.ttf (9,524KB) 壓縮成 simhei.zip (5,017KB)

XAML:

<TextBlock x:Name='text1' Canvas.Top='0' Canvas.Left='0' FontSize='34' Text='中文顯示' />

JavaScript:

TestText1.Scene.prototype =
{
    handleLoad: function(control, userContext, rootElement)
    {
        this.root = rootElement;
        this.downloader = this.control.createObject("downloader");
        this.downloader.addEventListener("Completed", Silverlight.createDelegate(this, this.handleCompleted));
        this.downloader.open("GET", "simhei.zip");
        this.downloader.send();
    },
    handleCompleted: function(sender, eventArgs)
    {
        var textblock = this.root.findName('text1');
        textblock.setFontSource(this.downloader);
        textblock.fontFamily = 'SimHei';
    },
}

這是修改範例程式 TileText 的結果: