1# XComponent 2 3 4As a drawing component, the \<[XComponent](../reference/arkui-ts/ts-basic-components-xcomponent.md)> is usually used to meet relatively complex drawing customization requirements, for example, display of a camera preview stream and drawing of a game image. 5 6 7You can specify the **type** parameter to implement different features. Two options are mainly available for this parameter: **surface** and **component**. 8 9 10With the **\<XComponent>** of the **surface** type, you can pass data to the surface independently owned by it to render the image. 11 12 13With the **\<XComponent>** of the **component** type, you can dynamically load the displayed content. 14 15 16## surface Type 17 18When the **\<XComponent>** is set to the **surface** type, you can write EGL/OpenGL ES and media data and display it on the **\<XComponent>**. 19 20You can also have the **\<XComponent>** laid out and rendered together with other components. 21 22The **\<XComponent>** has an independent surface, which provides a native window for you to create the EGL/OpenGL ES environment on the native (C/C++) side and use the standard OpenGL ES for development. 23 24In addition, media-related applications (such as videos and cameras) can write data to the surface provided by the **\<XComponent>** to present the corresponding image. 25 26 27## Using EGL/OpenGL ES for Rendering 28 29 30### Key Points of Native Code Development 31 32OpenHarmony applications use native APIs to implement interactions between JS and C/C++ code. This is also the case with the **\<XComponent>**. For details, see [Using N-APIs in Application Projects](../napi/napi-guidelines.md). 33 34The type of the file for processing the JS logic on the native side is .so. 35 36- Each module has a .so file. 37 38- The .so file is named in the format of lib{moduleName}.so. 39 40 41In the scenario where the **\<XComponent>** is used for standard OpenGL ES development, the content of the **CMAKELists.txt** file is as follows: 42 43 44 45``` 46cmake_minimum_required(VERSION 3.4.1) 47project(XComponent) # Project name 48 49set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) 50# Path for searching for header files 51include_directories(${NATIVERENDER_ROOT_PATH} 52 ${NATIVERENDER_ROOT_PATH}/include 53 ) 54 55# Compile the target .so file. SHARED indicates the dynamic library. 56add_library(nativerender SHARED 57 xxx.cpp 58 ) 59 60# Search for related libraries (including OpenGL ES libraries and NDK APIs provided by the <XComponent>). 61find_library( EGL-lib 62 EGL ) 63 64find_library( GLES-lib 65 GLESv3 ) 66 67find_library( libace-lib 68 ace_ndk.z ) 69 70# Dependencies required for compiling .so files 71target_link_libraries(nativerender PUBLIC ${EGL-lib} ${GLES-lib} ${libace-lib} libace_napi.z.so libc++.a) 72``` 73 74 75### Registering the N-API Module 76 77 78```c++ 79static napi_value Init(napi_env env, napi_value exports) 80{ 81 // Define the API exposed on the module. 82 napi_property_descriptor desc[] ={ 83 DECLARE_NAPI_FUNCTION("changeColor", PluginRender::NapiChangeColor), 84 }; 85 // You can mount the native method (PluginRender::NapiChangeColor) to exports through this API. exports is bound to a JS object at the JS layer through the JS engine. 86 NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); 87 return exports; 88} 89 90static napi_module nativerenderModule = { 91 .nm_version = 1, 92 .nm_flags = 0, 93 .nm_filename = nullptr, 94 .nm_register_func = Init, // Specify the callback for when the corresponding module is loaded. 95 .nm_modname = "nativerender", // Specify the module name. For <XComponent>-related development, the name must be the same as the value of libraryname in the <XComponent> on ArkTS. 96 .nm_priv = ((void*)0), 97 .reserved = { 0 }, 98}; 99 100extern "C" __attribute__((constructor)) void RegisterModule(void) 101{ 102 // Register the SO module. 103 napi_module_register(&nativerenderModule);c 104} 105``` 106 107 108### Parsing the NativeXComponent Instance 109 110**NativeXComponent** provides an instance at the native layer for the **\<XComponent>**, which can be used as a bridge for binding with the **\<XComponent>** at the JS layer. The NDK APIs provided by the **\<XComponent>** depend on this instance. For details about the NKD APIs, see [Native XComponent](../reference/native-apis/_o_h___native_x_component.md). 111 112 113The **NativeXComponent** instance can be obtained by parsing the callback (that is, the **Init** function in [NAPI module registration](#registering-the-n-api-module)) when the module is loaded. 114 115 116 117```c++ 118{ 119 // ... 120 napi_status status; 121 napi_value exportInstance = nullptr; 122 OH_NativeXComponent *nativeXComponent = nullptr; 123 // Parse the attribute of the wrapped NativeXComponent pointer. 124 status = napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance); 125 if (status != napi_ok) { 126 return false; 127 } 128 // Use the napi_unwrap API to parse the NativeXComponent instance pointer. 129 status = napi_unwrap(env, exportInstance, reinterpret_cast<void**>(&nativeXComponent)); 130 // ... 131} 132``` 133 134 135### Registering XComponent Callback 136 137Based on the NativeXComponent pointer obtained by [parsing the NativeXComponent instance](#parsing-the-nativexcomponent-instance), perform callback registration through the **OH_NativeXComponent_RegisterCallback** API. 138 139 140 141```c++ 142{ 143 ... 144 OH_NativeXComponent *nativeXComponent = nullptr; 145 // Parse the NativeXComponent instance. 146 147 OH_NativeXComponent_Callback callback; 148 callback->OnSurfaceCreated = OnSurfaceCreatedCB; // Invoked when a surface is successfully created. You can obtain the handle to the native window from this event. 149 callback->OnSurfaceChanged = OnSurfaceChangedCB; // Invoked when the surface changes. You can obtain the native window handle and XComponent change information from this event. 150 callback->OnSurfaceDestroyed = OnSurfaceDestroyedCB; // Invoked when the surface is destroyed. You can release resources in this event. 151 callback->DispatchTouchEvent = DispatchTouchEventCB; // Invoked when a touch event occurs. You can obtain the touch event information from this event. 152 153 OH_NativeXComponent_RegisterCallback(nativeXComponent, callback); 154 ... 155} 156``` 157 158 159### Creating the EGL/OpenGL ES Environment 160 161In the registered **OnSurfaceCreated** callback, you can obtain the handle to the native window (which is essentially the surface independently owned by the **\<XComponent>**). Therefore, you can create the EGL/OpenGL ES environment for your application to start the development of the rendering logic. 162 163 164```c++ 165EGLCore* eglCore_; // EGLCore is a class that encapsulates OpenGL-related APIs. 166uint64_t width_; 167uint64_t height_; 168void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window) 169{ 170 int32_t ret = OH_NativeXComponent_GetXComponentSize(component, window, &width_, &height_); 171 if (ret === OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { 172 eglCore_->GLContextInit(window, width_, height_); // Initialize the OpenGL environment. 173 } 174} 175``` 176 177 178### ArkTS Syntax 179 180You can use the **\<XComponent>** to develop EGL/OpenGL ES rendering by using the following code on the ArkTS side: 181 182 183```ts 184XComponent({ id: 'xcomponentId1', type: 'surface', libraryname: 'nativerender' }) 185 .onLoad((context) => {}) 186 .onDestroy(() => {}) 187``` 188 189- **id**: corresponds to an **\<XComponent>** and must be unique. Generally, you can use the **OH_NativeXComponent_GetXComponentId** API on the native side to obtain the corresponding ID and bind the corresponding **\<XComponent>**. 190 191- **libraryname**: name of the loaded module, which must be the same as the value of **nm_modname** used when the Napi module is registered on the native side. 192 >**NOTE** 193 > 194 > An application loads modules to implement cross-language invoking in either of the following ways: 195 > 196 > 1. Use the **import** mode of the NAPI. 197 > 198 > ```ts 199 > import nativerender from "libnativerender.so" 200 > ``` 201 > 202 > 2. Use the **\<XComponent>**, which, in essence, is to use the NAPI mechanism. 203 > The difference between this loading mode and the **import** loading mode is that when the dynamic library is loaded, the **NativeXComponent** instance of the **\<XComponent>** is exposed to the native layer of the application so that you can use the NDK APIs of the **\<XComponent>**. 204 205- onLoad event 206 - Trigger time: when the surface of the **\<XComponent>** is prepared. 207 - **context** parameter: where the native API exposed on the module is mounted. Its usage is similar to the usage of the **context2** instance obtained after the module is directly loaded using **import context2 from "libnativerender.so"**. 208 - Time sequence: When the **onLoad** event is subject to the surface. The following figure shows the time sequence of the **onLoad** event and the **OnSurfaceCreated** event on the native side. 209 210 ![onLoad](figures /onLoad.png) 211 212- onDestroy event 213 Trigger time: when the **\<XComponent>** is destroyed, in the same manner as that when an ArkUI component is destroyed. The following figure shows the time sequence of the **onDestroy** event and the **OnSurfaceDestroyed** event on the native side. 214 215 ![onDestroy](figures /onDestroy.png) 216 217 218### Writing Media Data 219 220The surface held by the **\<XComponent>** complies with the producer-consumer model. 221 222In OpenHarmony, components that comply with the producer design, such as the camera and video player, can write data to the surface held by the **\<XComponent>** and display the data through the **\<XComponent>**. 223 224![Picture 1](figures /Picture 1.png) 225 226You can bind the **\<XComponent>** to the **XComponentController** to obtain the surface ID (**surfaceId**, which uniquely identifies a surface) and send it to the corresponding component API. 227 228 229```ts 230@State surfaceId:string = ""; 231mXComponentController: XComponentController = new XComponentController(); 232XComponent({ id: '', type: 'surface', controller: this.mXComponentController }) 233 .onLoad(() => { 234 this.surfaceId = this.mXComponentController.getXComponentSurfaceId() 235 }) 236``` 237 238For details about component APIs, see [AVPlayer](../reference/apis/js-apis-media.md#avplayer9) and [Camera](../reference/apis/js-apis-camera.md). 239 240 241### component Type 242 243When the **\<XComponent>** is set to the **component** type, you can execute non-UI logic to dynamically load the displayed content. 244 245 246>**NOTE** 247> 248> When **type** is set to **component**, the **\<XComponent>** functions as a container, where child components are laid out vertically. 249> 250> - Vertical alignment: [FlexAlign](../reference/arkui-ts/ts-appendix-enums.md#flexalign).Start 251> 252> - Horizontal alignment: [FlexAlign](../reference/arkui-ts/ts-appendix-enums.md#flexalign).Center 253> 254> The component does not respond to any events. 255> 256> Layout changes and event responses can be set by mounting child components. 257> 258> The non-UI logic written internally needs to be encapsulated in one or more functions. 259 260 261### Example Scenario 262 263 264```ts 265@Builder 266function addText(label: string): void { 267 Text(label) 268 .fontSize(40) 269} 270 271@Entry 272@Component 273struct Index { 274 @State message: string = 'Hello XComponent' 275 @State messageCommon: string = 'Hello World' 276 build() { 277 Row() { 278 Column() { 279 XComponent({ id: 'xcomponentId-container', type: 'component' }) { 280 addText(this.message) 281 Divider() 282 .margin(4) 283 .strokeWidth(2) 284 .color('#F1F3F5') 285 .width("80%") 286 Column() { 287 Text(this.messageCommon) 288 .fontSize(30) 289 } 290 } 291 } 292 .width('100%') 293 } 294 .height('100%') 295 } 296} 297``` 298 299![en-us_image_0000001511900428](figures/en-us_image_0000001511900428.png) 300