目录

Window Layout

When to Use

Window layout refers to the capability of setting and managing the position and size attributes of windows. Through the window layout capability, you can flexibly control the display form of app windows on the screen, achieving diverse UI presentation effects.

Window layout mainly includes the following capabilities:

Proper use of window layout capabilities helps developers:

Managing the Window Size or Aspect Ratio Limits

By managing window size constraints or aspect ratio limits, you can restrict the adjustable range and display ratio of a window, preventing an excessively large or small window from affecting the user experience.

[h2]Window Size Constraints

WindowLimits represents the minimum and maximum size constraints of a window, including the minimum window height (minWindowHeight), maximum height (maxWindowHeight), minimum width (minWindowWidth), and maximum width (maxWindowWidth). You can use the getWindowLimits() and getWindowLimitsVP() APIs to query the current size constraints of a window.

The system provides multiple configuration methods for window size constraints. The final effective result of the window size constraints is obtained by taking the intersection of the following configurations, listed in descending order of priority:

Configuration Method Priority Unit Effective Timing When to Use

Call setWindowLimits() API with the input parameter windowLimits

Call setWindowLimits() API with the input parameters windowLimits and isForcible

Highest (setting during runtime)

px or vp

(specified via pixelUnit)

Takes effect dynamically after the window is created When window size constraints need to be dynamically adjusted based on runtime state, such as automatic adaptation based on content or adjustments after user interaction
Set via StartOptions when calling the startAbility() API Medium (set at startup) vp Takes effect when the ability starts When window size constraints need to be specified at startup, such as specifying the window size range when launching another app
Configured via the abilities tag in the module.json5 configuration file Low (static configuration) vp Takes effect after the app is installed

When window size constraints need to be preset, serving as the default configuration for the app

This takes effect for the main window corresponding to the current UIAbility.

Default system constraints Low (system default) vp Takes effect after the app is installed When the app does not need to specify window size constraints and follows the system default constraints (the system default constraints vary based on different products and window types).

[h2]Window Content Aspect Ratio Limit

The window aspect ratio limit applies to the following typical scenarios:

Currently, apps can call the following APIs to set the aspect ratio limit for the window content area.

API Function Applicable Scenario Effective Scope
setAspectRatio() Sets the aspect ratio of the window content layout (excluding decorations such as borders and title bars). This ratio parameter is persisted by default. - Configuring the same content aspect ratio for multiple launch instances of the same app. When a main window of the same app calls this API and the aspect ratio takes effect, subsequently opened main windows will continue to use this aspect ratio. Main window in Freeform Window state
setContentAspectRatio()

Sets the aspect ratio of the window content layout (excluding decorations such as borders and title bars).

The window width and height will adjust according to changes in the window border decoration size or visibility, and it supports configuring whether this ratio parameter is persisted.

- Customizing the main window title bar size and visibility

- Setting the aspect ratio for a single main window individually

Main window in Freeform Window state

Sample

// Index.ets
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

const DOMAIN = 0x0000;
const TAG = 'IndexPage';

// ...
  /**
   Step 2: Set the specified aspect ratio for the main window.
   */
  private setWindowAspectRatioEnabled(enabled: boolean): void {
    const mainWindow = this.getMainWindow();
    if (!mainWindow) {
      this.resultText = 'Main window not found';
      return;
    }
    if (enabled) {
      const ratio = 1.5;
      // Set the aspect ratio limit for the layout content.
      mainWindow.setAspectRatio(ratio)
        .then(() => {
          AppStorage.setOrCreate('WINDOW_ASPECT_RATIO_ENABLED', enabled);
          this.resultText = 'Aspect ratio limit enabled';
        })
        .catch((err: Error) => {
          const businessError = err as BusinessError;
          this.resultText = `Failed to set aspect ratio limit: ${JSON.stringify(businessError)}`;
          hilog.error(DOMAIN, TAG, `set aspect ratio failed: ${JSON.stringify(businessError)}`);
        });
    } else {
      // Cancel the aspect ratio limit for the layout content.
      mainWindow.resetAspectRatio()
        .then(() => {
          AppStorage.setOrCreate('WINDOW_ASPECT_RATIO_ENABLED', enabled);
          this.resultText = 'Aspect ratio limit disabled';
        })
        .catch((err: Error) => {
          const businessError = err as BusinessError;
          this.resultText = `Failed to reset aspect ratio limit: ${JSON.stringify(businessError)}`;
          hilog.error(DOMAIN, TAG, `reset aspect ratio failed: ${JSON.stringify(businessError)}`);
        });
    }
  }

Adjusting the Window Position and Size

[h2]Setting the Initial Position and Size of the Main Window at Startup

The initial position and size of an app window at startup can be set. This is available through the following two methods.

[h2]Dynamically Adjusting the Window Position and Size

After a window is created, you can dynamically adjust its position and size through APIs.

[h2]Changing the Window Position and Size by Dragging

Currently, the following two window dragging capabilities are provided.

[h2]Sensing the Window Position and Size Changes

Apps can sense changes in window position and size by actively querying, registering event listeners, or declaring environment variables, and then respond accordingly.

Currently, the following APIs are available for querying and listening to window position and size changes:

API Return Value Type Description
on('windowSizeChange') Size Listens to window size changes, in px.
on('windowRectChange') RectChangeOptions Listens to window rectangle (window position and window size) changes, returns the corresponding values and the reason for the change, in px.
on('rectChangeInGlobalDisplay') RectChangeOptions Listens to window rectangle (window position and window size) changes in the global coordinate system, returns the corresponding values and the reason for the change, in px.
getWindowProperties() WindowProperties

Obtains the properties of the current window. The properties related to window position and size are:

windowRect: The position and size of the window, relative to the current screen coordinate system.

drawableRect: The size of the drawable area within the window, where the left and top boundaries are calculated relative to the top-left vertex of the window. globalDisplayRect: The position and size of the window, relative to the global coordinate system.

Apps can also sense window position and size changes by using environment variables. Environment variables are a global state management mechanism. In multi-device development scenarios, you can use the @Env decorator to listen for changes in system environment variables and make corresponding scenario judgments based on them, thereby reducing adaptation logic and repetitive development across different devices. For details, see @Env: Environment Variables.

Environment variables allow components to perceive and respond to window size changes. When the window size changes, components that declare and use environment variables for layout can achieve responsive layout effects.

Environment Variable Return Type Description
SystemProperties.WINDOW_SIZE window.SizeInVP Window size, in vp. It contains width and height attributes.
SystemProperties.WINDOW_SIZE_PX window.Size Window size, in px. It contains width and height attributes.