HarmonyOS鸿蒙Next中NAPI如何获取设备的屏幕信息

HarmonyOS鸿蒙Next中NAPI如何获取设备的屏幕信息 NAPI如何获取设备的屏幕信息,包括有几块屏幕,屏幕的宽高等信息

3 回复

可以通过napi_load_module 的方式调用 系统 arkts的api 获取。

例如,以下是在native侧 通过napi_load_module 加载 @ohos.display 模块来获取屏幕宽高的demo:

#define LOGD(fmt, ...) OH_LOG_Print(LOG_APP, LOG_DEBUG, 1000, "TestTag", fmt, ##__VA_ARGS__)
static napi_value testDisplaySize(napi_env env, napi_callback_info info)
{
    // 获取arkts侧的系统库路径
    char path[64] = "[@ohos](/user/ohos).display";
    size_t typeLen = 0;
    napi_value string;
    napi_create_string_utf8(env, path, typeLen, &string);

    // 加载系统库
    napi_value result;
    napi_load_module(env, path, &result);

    // 获取系统库中的"getDefaultDisplaySync"方法
    napi_value func = nullptr;
    napi_get_named_property(env, result, "getDefaultDisplaySync", &func);

    napi_value funcResult;
    napi_call_function(env, result, func, 0, nullptr, &funcResult);

    napi_value widthValue = nullptr;
    napi_get_named_property(env, funcResult, "width", &widthValue);

    double width;
    napi_get_value_double(env, widthValue, &width);
    LOGD("width : %{public}f", width);

    napi_value heightValue = nullptr;
    napi_get_named_property(env, funcResult, "height", &heightValue);

    double height;
    napi_get_value_double(env, heightValue, &height);
    LOGD("height : %{public}f", height);

    return nullptr;
}

更多关于HarmonyOS鸿蒙Next中NAPI如何获取设备的屏幕信息的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,使用NAPI(Native API)获取设备的屏幕信息可以通过以下步骤实现:

  1. 引入相关模块:首先,需要引入@ohos.window模块,该模块提供了与窗口和屏幕相关的API。

  2. 获取窗口对象:通过window.getLastWindow方法获取当前窗口对象。

  3. 获取屏幕信息:使用窗口对象的getWindowProperties方法获取窗口属性,其中包括屏幕的宽高、密度等信息。

示例代码如下:

import window from '@ohos.window';

// 获取当前窗口对象
let windowClass = window.getLastWindow();

// 获取窗口属性
let windowProperties = windowClass.getWindowProperties();

// 获取屏幕宽度和高度
let screenWidth = windowProperties.windowRect.width;
let screenHeight = windowProperties.windowRect.height;

// 获取屏幕密度
let screenDensity = windowProperties.density;

在上述代码中,windowRect属性包含了屏幕的宽度和高度信息,density属性表示屏幕的密度。通过这些属性,可以获取到设备的屏幕信息。

注意:以上代码仅为示例,实际使用时需根据具体场景进行调整。

在HarmonyOS鸿蒙Next中,通过NAPI获取设备屏幕信息,可以使用@ohos.display模块的getDefaultDisplaySync方法。首先,导入@ohos.display模块,然后调用getDefaultDisplaySync获取默认显示对象,最后通过该对象的属性(如widthheightdensityDPI等)获取屏幕分辨率、像素密度等信息。示例代码如下:

import display from '@ohos.display';

let displayInfo = display.getDefaultDisplaySync();
console.log(\`Screen width: \${displayInfo.width}, height: \${displayInfo.height}, DPI: \${displayInfo.densityDPI}\`);

此代码将输出设备的屏幕宽度、高度和DPI值。

回到顶部