依瀏覽器大小, 自動等比例調整 Silverlight 區塊

用 Blend 所設計出來的 XAML 都是設定成 640 x 480 的大小,  而 XAML 是向量格式的圖形, 理論上是可以隨瀏覽器的大小自由縮放, 這裡的範例會用到瀏覽器的 window.onresize 的事件接收視窗大小改變的事件, 以及 XAML 的 <ScaleTransform /> 設定整個 XAML 的縮放比例。

以下範例是用 Blend 2 Sep. CTP 建立新的 Project,

Page.xaml.js:

註冊一個 onresize 事件到 Silverlight Object, 在每次瀏覽器視窗改變時, 讀取 Silverlight Object 的  actualWidth 與  actualHeight, 以計算 ScaleTransform 的縮放比例。只有在初始時 (onload時), actualWidth 及 actualHeight 皆為 0, 所以初始時先用 control 的 offsetWidth 與 offsetHeight。之後的 onresize 時, 改用 actualWidth 與 actualHeight, 才能在全螢幕時抓到正確的大小。

if (!window.AlbumProject)
    window.AlbumProject = {};

AlbumProject.Page = function()
{
}

AlbumProject.Page.prototype =

    handleLoad: function(control, userContext, rootElement)
    {
        this.control = control;
        this.rootElement = rootElement;
        if (this.rootElement.RenderTransform == null)
            this.rootElement.RenderTransform=this.control.content.createFromXaml('<ScaleTransform ScaleX="1" ScaleY="1"/>');
        this.control.content.onresize = Silverlight.createDelegate(this, this.handleResize);
        this.handleResize(this);
        rootElement.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleMouseDown));
    },
    handleResize: function(sender)
    {
        var height = this.control.content.actualHeight > 0 ? this.control.content.actualHeight : this.control.offsetHeight;
        var width = this.control.content.actualWidth > 0 ? this.control.content.actualWidth : this.control.offsetWidth;
        var heightRate = height / this.rootElement.height;
        var widthRate = width / this.rootElement.width;
        var scaleRate = heightRate < widthRate ? heightRate : widthRate;
        this.rootElement.RenderTransform.scaleX = this.rootElement.RenderTransform.scaleY = scaleRate;

        this.rootElement["Canvas.Left"] = (width - this.rootElement.width * scaleRate) / 2;
    },
    handleMouseDown: function(sender, eventArgs)
    {
        this.control.content.FullScreen = true;
        this.handleResize(this);
    }

}

Default.html:

將 silverlightHost 的 height 與 width 成 100%, 好讓 Silverlight control 隨著 html 自動縮放, 並刪除 , <html /> 之前的 <!DOCTYPE ...>。

注意: 如果不刪 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">, 雖然在 IE 上不會有問題, 但在 Firefox 上則無法正常運作, 因為 Firefox 遇到 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional"> 時, html 的大小會有不同的解釋。

<html xmlns="https://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript" src="Silverlight.zh-cht.js"></script>
    <script type="text/javascript" src="Default_html.js"></script>
    <script type="text/javascript" src="Page.xaml.js"></script>
    <style type="text/css">
        .silverlightHost {
            height: 100%;
            width: 100%;
        }
    </style>
</head>

<body>
    <div id="SilverlightControlHost" class="silverlightHost">
        <script type="text/javascript">
            createSilverlight();
        </script>
    </div>
</body>
</html>