乐闻世界logo
搜索文章和话题

How to get the screen width and height of the device in HarmonyOS?

1个答案

1

Obtaining the screen width and height of a device in HarmonyOS can be achieved through the DisplayManager and Display classes. This process can be broken down into the following steps:

  1. Obtain a DisplayManager instance: First, obtain an instance of DisplayManager from the system service.

  2. Get the default display device: Use DisplayManager to retrieve the default display device, which is typically the main screen of the device.

  3. Read the screen dimensions: Extract the width and height of the screen from the obtained Display object.

Below is a specific code example demonstrating how to implement this process in HarmonyOS:

java
import ohos.aafwk.ability.Ability; import ohos.agp.window.service.Display; import ohos.agp.window.service.DisplayManager; import ohos.agp.window.service.Window; import ohos.app.Context; public class ScreenUtils { /** * Get screen width * @param context Context object * @return Screen width */ public static int getScreenWidth(Context context) { DisplayManager displayManager = DisplayManager.getInstance(); Display defaultDisplay = displayManager.getDefaultDisplay(context).get(); return defaultDisplay.getWidth(); } /** * Get screen height * @param context Context object * @return Screen height */ public static int getScreenHeight(Context context) { DisplayManager displayManager = DisplayManager.getInstance(); Display defaultDisplay = displayManager.getDefaultDisplay(context).get(); return defaultDisplay.getHeight(); } }

In the above code, we first obtain an instance of DisplayManager using DisplayManager.getInstance(). Then, we use the getDefaultDisplay() method to retrieve the default display device, which is typically the main screen of the device. Finally, we extract the screen width and height using the getWidth() and getHeight() methods respectively.

This approach is straightforward and enables quick retrieval of screen dimension information. When developing applications, understanding screen dimensions is particularly valuable for responsive design or dynamic layouts.

2024年7月26日 22:28 回复

你的答案