鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之XComponent组件

695 阅读3分钟

鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之XComponent组件

一、操作环境

操作系统:  Windows 10 专业版、IDE:DevEco Studio 3.1、SDK:HarmonyOS 3.1+

二、XComponent组件

可用于EGL/OpenGLES和媒体数据写入,并显示在XComponent组件。

子组件

构造参数type为"surface"时不支持。

从API version 9开始,构造参数type为"component"时可以包含子组件。

接口

XComponent(value: {id: string, type: string, libraryname?: string, controller?: XComponentController})

参数

参数名参数类型必填描述
idstring组件的唯一标识,支持最大的字符串长度128。
typestring用于指定XComponent组件类型,可选值为:-"surface":用于EGL/OpenGLES和媒体数据写入,组件内容单独送显,直接合成到屏幕。-"component"9+ :XComponent将变成一个容器组件,并可在其中执行非UI逻辑以动态加载显示内容。
librarynamestring应用Native层编译输出动态库名称,仅XComponent类型为"surface"时有效。
controllerXComponentcontroller给组件绑定一个控制器,通过控制器调用组件方法,仅XComponent类型为"surface"时有效。

说明

type为"component"时,XComponent作为容器,子组件沿垂直方向布局:

  • 垂直方向上对齐格式:FlexAlign.Start
  • 水平方向上对齐格式:FlexAlign.Center

所有的事件响应均不支持。

布局方式更改和事件响应均可通过挂载子组件来设置。

内部所写的非UI逻辑需要封装在一个或多个函数内。

属性

  • XComponent显示的内容,可由开发者自定义绘制,通用属性不支持背景设置透明度设置图像效果
  • type为"surface"时建议使用EGL/OpenGLES提供的接口设置相关内容。
  • type为"component"时建议使用挂载子组件的方式进行设置相关内容。

事件

仅type为"surface"时以下事件有效。不支持通用事件手势

onLoad

onLoad(callback: (event?: object) => void )

插件加载完成时回调事件。

参数
参数名参数类型必填描述
eventobject获取XComponent实例对象的context,context上挂载的方法由开发者在c++层定义。
onDestroy

onDestroy(event: () => void )

插件卸载完成时回调事件。

XComponentController

xcomponent 组件的控制器,可以将此对象绑定至XComponent组件,然后通过控制器来调用组件方法。

创建对象
  1. xcomponentController: XComponentController = new XComponentController()

getXComponentSurfaceId

getXComponentSurfaceId(): string

获取XComponent对应Surface的ID,供@ohos接口使用,仅XComponent类型为"surface"时有效。

返回值
类型描述
stringXComponent持有Surface的ID。

setXComponentSurfaceSize

setXComponentSurfaceSize(value: {surfaceWidth: number, surfaceHeight: number}): void

设置XComponent持有Surface的宽度和高度,仅XComponent类型为"surface"时有效。

参数
参数名参数类型必填描述
surfaceWidthnumberXComponent持有Surface的宽度。
surfaceHeightnumberXComponent持有Surface的高度。

getXComponentContext

getXComponentContext(): Object

获取XComponent实例对象的context,仅XComponent类型为"surface"时有效。
返回值
类型描述
Object获取XComponent实例对象的context,context包含的具体接口方法由开发者自定义。

示例

代码

// xxx.ets
@Entry
@Component
struct PreviewArea {
  private surfaceId : string =''
  xcomponentController: XComponentController = new XComponentController()
  build() {
    Row() {
      XComponent({
        id: 'xcomponent',
        type: 'surface',
        controller: this.xcomponentController
      })
        .onLoad(() => {
          this.xcomponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080});
          this.surfaceId = this.xcomponentController.getXComponentSurfaceId()
        })
        .width('640px')
        .height('480px')
    }
    .backgroundColor(Color.Black)
    .position({x: 0, y: 48})
  }
}

你有时间常去我家看看我在这里谢谢你啦...

我家地址:亚丁号

最后送大家一首诗:

山高路远坑深,
大军纵横驰奔,

谁敢横刀立马?
惟有点赞加关注大军。