在Metro应用程序中获取窗口尺寸

Getting window dimensions in a Metro app

本文关键字:窗口 获取 Metro 应用程序      更新时间:2024-02-02

如何在windows 8 metro应用程序中获取窗口的尺寸?

我想用画布元素填充屏幕,目前我的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 ...

要获得大小,您需要:

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

物理尺寸可以通过以下方式获得:

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

我已经在几种屏幕尺寸上尝试过了,在大多数情况下,physicalSize都是准确的,有时会有0.1英寸的错误。

我希望它能有所帮助。

以下JavaScript代码应该可以工作:

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

如果您想根据比例调整画布的大小,也可以使用resolutionScale枚举:

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