#鸿蒙通关秘籍#如何在HarmonyOS使用XComponent实现EGL/OpenGLES渲染?

HarmonyOS
2024-12-04 14:44:00
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
SCM梦海

要在HarmonyOS中利用XComponent进行EGL/OpenGLES渲染,遵循以下步骤:

  1. 在CMAKELists.txt中配置相关依赖项,并编译所需的动态库:

    cmake_minimum_required(VERSION 3.4.1)
    project(XComponent)
    
    set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})
    include_directories(${NATIVERENDER_ROOT_PATH}
                        ${NATIVERENDER_ROOT_PATH}/include)
    
    add_library(nativerender SHARED
                xxx.cpp
                )
    
    find_library(EGL-lib EGL)
    find_library(GLES-lib GLESv3)
    find_library(libace-lib ace_ndk.z)
    
    target_link_libraries(nativerender PUBLIC ${EGL-lib} ${GLES-lib} ${libace-lib} libace_napi.z.so libc++.a)
    
  2. 注册Napi模块并解析XComponent的NativeXComponent:

    static napi_value Init(napi_env env, napi_value exports) {
        napi_property_descriptor desc[] = {
            DECLARE_NAPI_FUNCTION("changeColor", PluginRender::NapiChangeColor),
        };
        NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
        return exports;
    }
    
    static napi_module nativerenderModule = {
        .nm_version = 1,
        .nm_flags = 0,
        .nm_filename = nullptr,
        .nm_register_func = Init,
        .nm_modname = "nativerender",
        .nm_priv = ((void*)0),
        .reserved = {0},
    };
    
    extern "C" __attribute__((constructor)) void RegisterModule(void) {
        napi_module_register(&nativerenderModule);
    }
    
  3. 注册XComponent的事件回调:

    {
        OH_NativeXComponent *nativeXComponent = nullptr;
    
        OH_NativeXComponent_Callback callback;
        callback->OnSurfaceCreated = OnSurfaceCreatedCB;
        callback->OnSurfaceChanged = OnSurfaceChangedCB;
        callback->OnSurfaceDestroyed = OnSurfaceDestroyedCB;
        callback->DispatchTouchEvent = DispatchTouchEventCB;
    
        OH_NativeXComponent_RegisterCallback(nativeXComponent, callback);
    }
    
  4. 创建EGL/OpenGLES环境,在OnSurfaceCreatedCB回调中初始化OpenGL环境:

    EGLCore* eglCore_;
    uint64_t width_;
    uint64_t height_;
    
    void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window) {
        int32_t ret = OH_NativeXComponent_GetXComponentSize(component, window, &width_, &height_);
        if (ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
            eglCore_->GLContextInit(window, width_, height_);
        }
    }
    
  5. 在ArkTS侧使用XComponent组件进行渲染开发:

    XComponent({ id: 'xcomponentId1', type: 'surface', libraryname: 'nativerender' })
      .onLoad((context) => {})
      .onDestroy(() => {})
    
分享
微博
QQ
微信
回复
2024-12-04 16:31:37
相关问题
使用Native、XComponentEGL绘制图形
1157浏览 • 1回复 待解决