2012-07-24 72 views
1

如何在Windows 8 metro應用程序中獲取窗口的尺寸?在Metro應用程序中獲取窗口尺寸

我想填補一個canvas元素的屏幕,目前我的default.js文件看起來像這樣

// ... some autogenerated code ... 
app.onactivated = function (args) { 
    if (args.detail.kind === activation.ActivationKind.launch) { 
    // ... some autogenerated code ... 

    var canvas = document.getElementById("myCanvas"); 
    var context = canvas.getContext("2d"); 

    canvas.width = 600; // I want to set width and height here so that 
    canvas.height = 800; // canvas fills the entire screen/window. 
}; 
// ... more autogenerated code ... 

回答

3

爲了得到大小,您需要:與規模因素已經應用

window.outerWidth 
window.outerHeight 

這將返回邏輯大小。

請注意,您還想要查看視圖狀態更改,並且當您輸入/離開快照,填充,完整模式以確保您的UI調整爲新的窗口大小。

具體來說,您需要可以使用CSS媒體查詢匹配:

var snappedNotification = matchMedia("all and (-ms-view-state: snapped)"); 
snappedNotification.addEventListener(mySnappedFunction); 

或者聽window.resize,並使用當前視圖狀態來看待當前視圖:

var currentViewState = Windows.UI.ViewManagement.ApplicationView.value; 

http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.viewmanagement.applicationviewstate.aspx

0

下面的JavaScript代碼應工作:

var height = $('#bodyTag').outerHeight(true); 

var width = $('#bodyTag').outerWidth(true); 

您也可以使用resolutionScale枚舉如果您想根據比例尺劃分您的畫布尺寸:

var resolutionScale = Windows.Graphics.Display.DisplayProperties.resolutionScale; 
+0

如果你使用JQuery,這隻會工作。 window.outerWidth/outerHeight是你需要的 – 2012-07-24 15:26:14

1

物理尺寸可以這樣獲得:

var displayInformation = Windows.Graphics.Display.DisplayInformation.getForCurrentView(); 
var scale = displayInformation.resolutionScale; 
var height = Math.ceil(window.outerHeight * scale/100); 
var width = Math.ceil(window.outerWidth * scale/100); 

var physicalWidth = width/displayInformation.rawDpiX; // in inches 
var physicalHeight = height/displayInformation.rawDpiY; // in inches 
var physicalSize = Math.floor(Math.sqrt(Math.pow(physicalWidth, 2) + Math.pow(physicalHeight, 2)) * 10)/10; // in inches 

我已經在幾種屏幕尺寸上試過這個,在大多數情況下,物理尺寸都是準確的,有時候會出現0.1「的錯誤。

我希望它可以幫助。