XComponent
组件作为一种绘制组件,通常用于满足用户复杂的自定义绘制需求,其主要有两种类型"surface和component。对于surface类型可以将相关数据传入XComponent单独拥有的NativeWindow来渲染画面。
由于上层UI是采用arkTS开发,那么想要使用XComponent的话,就需要一个桥接和native层交互,类似Android的JNI,鸿蒙应用可以使用napi接口来处理js和native层的交互。
1. 编写CMAKELists.txt文件
# the minimum version of CMake.
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
)
# 编译目标so动态库
add_library(nativerender SHARED
samples/minute_view.cpp
plugin/plugin_manager.cpp
common/HuMarketMinuteData.cpp
common/MinuteItem.cpp
napi_init.cpp
)
# 查找需要的公共库
find_library(
# Sets the name of the path variable.
hilog-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
hilog_ndk.z
)
#编译so所需要的依赖
target_link_libraries(nativerender PUBLIC
libc++.a
${hilog-lib}
libace_napi.z.so
libace_ndk.z.so
libnative_window.so
libnative_drawing.so
)
2. Napi模块注册
#include <hilog/log.h>
#include "plugin/plugin_manager.h"
#include "common/log_common.h"
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Init", "Init begins");
if ((nullptr == env) || (nullptr == exports)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Init", "env or exports is null");
return nullptr;
}
PluginManager::GetInstance()->Export(env, exports);
return exports;
}
EXTERN_C_END
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);
}
定义napi_module信息,里面包含模块名称(和arkts侧使用时的libraryname要保持一致),加载模块时的回调函数即Init()。然后注册so模块napi_module_register(&nativerenderModule), 接口Init()函数会收到回调,在Init()有两个参数:
- env: napi上下文环境;
- exports: 用于挂载native函数将其导出,会通过js引擎绑定到js层的一个js对象;
3.解析XComponent组件的NativeXComponent实例
if ((env == nullptr) || (exports == nullptr)) {
DRAWING_LOGE("Export: env or exports is null");
return;
}
napi_value exportInstance = nullptr;
// 用来解析出被wrap了NativeXComponent指针的属性
if (napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance) != napi_ok) {
DRAWING_LOGE("Export: napi_get_named_property fail");
return;
}
OH_NativeXComponent *nativeXComponent = nullptr;
// 通过napi_unwrap接口,解析出NativeXComponent的实例指针
if (napi_unwrap(env, exportInstance, reinterpret_cast<void **>(&nativeXComponent)) != napi_ok) {
DRAWING_LOGE("Export: napi_unwrap fail");
return;
}
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {'\0'};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(nativeXComponent, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
DRAWING_LOGE("Export: OH_NativeXComponent_GetXComponentId fail");
return;
}
4.注册XComponent事件回调
void MinuteView::RegisterCallback(OH_NativeXComponent *nativeXComponent) {
DRAWING_LOGI("register callback");
renderCallback_.OnSurfaceCreated = OnSurfaceCreatedCB;
renderCallback_.OnSurfaceDestroyed = OnSurfaceDestroyedCB;
renderCallback_.DispatchTouchEvent = nullptr;
renderCallback_.OnSurfaceChanged = OnSurfaceChanged;
// 注册XComponent事件回调
OH_NativeXComponent_RegisterCallback(nativeXComponent, &renderCallback_);
}
在事件回调中可以获取组件的宽高信息:
tatic void OnSurfaceCreatedCB(OH_NativeXComponent *component, void *window) {
DRAWING_LOGI("OnSurfaceCreatedCB");
if ((component == nullptr) || (window == nullptr)) {
DRAWING_LOGE("OnSurfaceCreatedCB: component or window is null");
return;
}
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {'\0'};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
DRAWING_LOGE("OnSurfaceCreatedCB: Unable to get XComponent id");
return;
}
std::string id(idStr);
auto render = MinuteView::GetInstance(id);
OHNativeWindow *nativeWindow = static_cast<OHNativeWindow *>(window);
render->SetNativeWindow(nativeWindow);
uint64_t width;
uint64_t height;
int32_t xSize = OH_NativeXComponent_GetXComponentSize(component, window, &width, &height);
if ((xSize == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) && (render != nullptr)) {
render->SetHeight(height);
render->SetWidth(width);
}
}
5.导出Native函数
void MinuteView::Export(napi_env env, napi_value exports) {
if ((env == nullptr) || (exports == nullptr)) {
DRAWING_LOGE("Export: env or exports is null");
return;
}
napi_property_descriptor desc[] = {
{"draw", nullptr, MinuteView::NapiDraw, nullptr, nullptr, nullptr, napi_default, nullptr}};
napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
if (napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc) != napi_ok) {
DRAWING_LOGE("Export: napi_define_properties failed");
}
}
6.在NapiDraw中绘制分时图
- 1.读取arkts侧透传过来的数据
vector<HuMarketMinuteData *> myVector;
size_t argc = 3;
napi_value args[3] = {nullptr};
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
napi_value vec = args[0]; // vector
napi_value vecNum = args[1]; // length
uint32_t vecCNum = 0;
napi_get_value_uint32(env, vecNum, &vecCNum);
for (uint32_t i = 0; i < vecCNum; i++) {
napi_value vecData;
napi_get_element(env, vec, i, &vecData);
HuMarketMinuteData *minuteData = new HuMarketMinuteData(&env, vecData);
myVector.push_back(minuteData);
}
#include "HuMarketMinuteData.h"
#include "common/MinuteItem.h"
#include "napi/native_api.h"
HuMarketMinuteData::HuMarketMinuteData(napi_env *env, napi_value value) {
napi_value api_date, api_isDateChanged, api_yclosePrice, api_minuteItems;
napi_get_named_property(*env, value, "date", &api_date);
napi_get_named_property(*env, value, "isDateChanged", &api_isDateChanged);
napi_get_named_property(*env, value, "yClosePrice", &api_yclosePrice);
napi_get_named_property(*env, value, "minuteList", &api_minuteItems);
uint32_t *uint32_date;
napi_get_value_uint32(*env, api_date, uint32_date);
date = int(*uint32_date);
napi_get_value_double(*env, api_yclosePrice, &yClosePrice);
uint32_t length;
napi_get_array_length(*env, api_minuteItems, &length);
for (uint32_t i = 0; i < length; i++) {
napi_value api_minuteItem;
napi_get_element(*env, api_minuteItems, i, &api_minuteItem);
MinuteItem *minuteItem = new MinuteItem(env, api_minuteItem);
minuteList.push_back(minuteItem);
}
}
HuMarketMinuteData::~HuMarketMinuteData() {
for (MinuteItem *item : minuteList) {
delete item;
item = nullptr;
}
}
- 2.绘制分时图
void MinuteView::Drawing2(vector<HuMarketMinuteData *>& minuteDatas) {
if (nativeWindow_ == nullptr) {
DRAWING_LOGE("nativeWindow_ is nullptr");
return;
}
int ret = OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow_, &buffer_, &fenceFd_);
DRAWING_LOGI("request buffer ret = %{public}d", ret);
bufferHandle_ = OH_NativeWindow_GetBufferHandleFromNative(buffer_);
mappedAddr_ = static_cast<uint32_t *>(
mmap(bufferHandle_->virAddr, bufferHandle_->size, PROT_READ | PROT_WRITE, MAP_SHARED, bufferHandle_->fd, 0));
if (mappedAddr_ == MAP_FAILED) {
DRAWING_LOGE("mmap failed");
}
// 创建一个bitmap对象
cBitmap_ = OH_Drawing_BitmapCreate();
// 定义bitmap的像素格式
OH_Drawing_BitmapFormat cFormat{COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUE};
// 构造对应格式的bitmap,width的值必须为 bufferHandle->stride / 4
OH_Drawing_BitmapBuild(cBitmap_, width_, height_, &cFormat);
// 创建一个canvas对象
cCanvas_ = OH_Drawing_CanvasCreate();
// 将画布与bitmap绑定,画布画的内容会输出到绑定的bitmap内存中
OH_Drawing_CanvasBind(cCanvas_, cBitmap_);
// 清除画布内容
OH_Drawing_CanvasClear(cCanvas_, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0xFF, 0xFF));
float padding = 30, with = width_, height = height_ / 2;
float ltX = padding, ltY = 1, rtX = with - padding,rtY = 1,lbX = padding,lbY = height - 1,rbX = with - padding,rbY = height - 1;
// 创建一个path对象
cPath_ = OH_Drawing_PathCreate();
// 指定path的起始位置
OH_Drawing_PathMoveTo(cPath_, ltX, ltY);
// 用直线连接到目标点
OH_Drawing_PathLineTo(cPath_, rtX, rtY);
OH_Drawing_PathLineTo(cPath_, rbX, rbY);
OH_Drawing_PathLineTo(cPath_, lbX, lbY);
// 闭合形状,path绘制完毕
OH_Drawing_PathClose(cPath_);
OH_Drawing_PathMoveTo(cPath_, padding, height / 2);
OH_Drawing_PathLineTo(cPath_, with - padding, height / 2);
OH_Drawing_PathMoveTo(cPath_, with / 2, 1);
OH_Drawing_PathLineTo(cPath_, with / 2, height - 1);
// 创建一个画笔Pen对象,Pen对象用于形状的边框线绘制
cPen_ = OH_Drawing_PenCreate();
OH_Drawing_PenSetAntiAlias(cPen_, true);
OH_Drawing_PenSetColor(cPen_, OH_Drawing_ColorSetArgb(0xFF, 0xE6, 0xE6, 0xE6));
OH_Drawing_PenSetWidth(cPen_, 2.0);
OH_Drawing_PenSetJoin(cPen_, LINE_ROUND_JOIN);
// 将Pen画笔设置到canvas中
OH_Drawing_CanvasAttachPen(cCanvas_, cPen_);
OH_Drawing_CanvasDrawPath(cCanvas_, cPath_);
double minPrice, maxPrice;
computeMaxMin(minuteDatas, &minPrice, &maxPrice);
OH_Drawing_Path *pricePath_ = OH_Drawing_PathCreate();
OH_Drawing_Path *avgPath_ = OH_Drawing_PathCreate();
// 指定path的起始位置
HuMarketMinuteData *minuteData = minuteDatas[0];
// 单位长度
float unitHeight = height / (maxPrice - minPrice);
float itemWidth = (with - 2 * padding) / (240 * minuteDatas.size());
float pointX = padding;
float pointY = 0;
float avg_pointX = padding;
float avg_pointY = 0;
bool isFirst = true;
float yClosePrice = 0;
for (int i = 0; i < minuteDatas.size(); i++) {
HuMarketMinuteData *minuteData = minuteDatas[i];
if (i == 0) {
yClosePrice = minuteData->yClosePrice;
}
if (minuteData != nullptr) {
for (int j = 0; j < minuteData->minuteList.size(); j++) {
MinuteItem *minuteItem = minuteData->minuteList[j];
if (minuteItem != nullptr) {
pointY = (maxPrice - minuteItem->nowPrice) * unitHeight;
avg_pointY = (maxPrice - minuteItem->avgPrice) * unitHeight;
if (isFirst) {
isFirst = false;
OH_Drawing_PathMoveTo(pricePath_, pointX, pointY);
OH_Drawing_PathMoveTo(avgPath_, avg_pointX, avg_pointY);
} else {
OH_Drawing_PathLineTo(pricePath_, pointX, pointY);
OH_Drawing_PathLineTo(avgPath_, avg_pointX, avg_pointY);
}
pointX += itemWidth;
avg_pointX += itemWidth;
}
}
}
}
// 创建一个画笔Pen对象,Pen对象用于形状的边框线绘制
cPen_ = OH_Drawing_PenCreate();
OH_Drawing_PenSetAntiAlias(cPen_, true);
OH_Drawing_PenSetColor(cPen_, OH_Drawing_ColorSetArgb(0xFF, 0x22, 0x77, 0xcc));
OH_Drawing_PenSetWidth(cPen_, 5.0);
OH_Drawing_PenSetJoin(cPen_, LINE_ROUND_JOIN);
// 将Pen画笔设置到canvas中
OH_Drawing_CanvasAttachPen(cCanvas_, cPen_);
// 在画布上画Price
OH_Drawing_CanvasDrawPath(cCanvas_, pricePath_);
OH_Drawing_PenSetColor(cPen_, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0x9D, 0x03));
OH_Drawing_CanvasAttachPen(cCanvas_, cPen_);
OH_Drawing_CanvasDrawPath(cCanvas_, avgPath_);
OH_Drawing_PathLineTo(pricePath_, pointX, height);
OH_Drawing_PathLineTo(pricePath_, padding, height);
OH_Drawing_PathClose(pricePath_);
OH_Drawing_CanvasDrawShadow(cCanvas_, pricePath_, {5, 5, 5}, {15, 15, 15}, 30,
OH_Drawing_ColorSetArgb(0x00, 0xFF, 0xff, 0xff),
OH_Drawing_ColorSetArgb(0x33, 0x22, 0x77, 0xcc), SHADOW_FLAGS_TRANSPARENT_OCCLUDER);
// 选择从左到右/左对齐等排版属性
OH_Drawing_TypographyStyle *typoStyle = OH_Drawing_CreateTypographyStyle();
OH_Drawing_SetTypographyTextDirection(typoStyle, TEXT_DIRECTION_LTR);
OH_Drawing_SetTypographyTextAlign(typoStyle, TEXT_ALIGN_LEFT);
// 设置文字颜色,例如黑色
OH_Drawing_TextStyle *txtStyle = OH_Drawing_CreateTextStyle();
OH_Drawing_SetTextStyleColor(txtStyle, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0x9D, 0x03));
// 设置文字大小、字重等属性
double fontSize = width_ / 15;
OH_Drawing_SetTextStyleFontSize(txtStyle, fontSize);
OH_Drawing_SetTextStyleFontWeight(txtStyle, FONT_WEIGHT_400);
OH_Drawing_SetTextStyleBaseLine(txtStyle, TEXT_BASELINE_ALPHABETIC);
OH_Drawing_SetTextStyleFontHeight(txtStyle, 1);
// 如果需要多次测量,建议fontCollection作为全局变量使用,可以显著减少内存占用
OH_Drawing_FontCollection *fontCollection = OH_Drawing_CreateSharedFontCollection();
// 注册自定义字体
const char *fontFamily = "myFamilyName"; // myFamilyName为自定义字体的family name
const char *fontPath = "/data/storage/el2/base/haps/entry/files/myFontFile.ttf"; // 设置自定义字体所在的沙箱路径
OH_Drawing_RegisterFont(fontCollection, fontFamily, fontPath);
// 设置系统字体类型
const char *systemFontFamilies[] = {"Roboto"};
OH_Drawing_SetTextStyleFontFamilies(txtStyle, 1, systemFontFamilies);
OH_Drawing_SetTextStyleFontStyle(txtStyle, FONT_STYLE_NORMAL);
OH_Drawing_SetTextStyleLocale(txtStyle, "en");
// 设置自定义字体类型
auto txtStyle2 = OH_Drawing_CreateTextStyle();
OH_Drawing_SetTextStyleFontSize(txtStyle2, fontSize);
const char *myFontFamilies[] = {"myFamilyName"}; // 如果已经注册自定义字体,填入自定义字体的family
// name使用自定义字体
OH_Drawing_SetTextStyleFontFamilies(txtStyle2, 1, myFontFamilies);
OH_Drawing_TypographyCreate *handler = OH_Drawing_CreateTypographyHandler(typoStyle, fontCollection);
OH_Drawing_TypographyHandlerPushTextStyle(handler, txtStyle);
OH_Drawing_TypographyHandlerPushTextStyle(handler, txtStyle2);
// 设置文字内容
const char *text = doubleToStringWithPrecision(yClosePrice, 2).c_str();
OH_Drawing_TypographyHandlerAddText(handler, text);
OH_Drawing_TypographyHandlerPopTextStyle(handler);
OH_Drawing_Typography *typography = OH_Drawing_CreateTypography(handler);
// 设置页面最大宽度
double maxWidth = width_;
OH_Drawing_TypographyLayout(typography, maxWidth);
// 设置文本在画布上绘制的起始位置
double position[2] = {100, height / 2.0};
// 将文本绘制到画布上
OH_Drawing_TypographyPaint(typography, cCanvas_, position[0], position[1]);
void *bitmapAddr = OH_Drawing_BitmapGetPixels(cBitmap_);
uint32_t *value = static_cast<uint32_t *>(bitmapAddr);
uint32_t *pixel = static_cast<uint32_t *>(mappedAddr_);
if (pixel == nullptr) {
DRAWING_LOGE("pixel is null");
return;
}
if (value == nullptr) {
DRAWING_LOGE("value is null");
return;
}
for (uint32_t x = 0; x < width_; x++) {
for (uint32_t y = 0; y < height_; y++) {
*pixel++ = *value++;
}
}
Region region{nullptr, 0};
OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer_, fenceFd_, region);
int result = munmap(mappedAddr_, bufferHandle_->size);
if (result == -1) {
DRAWING_LOGE("munmap failed!");
}
}
绘制流程:
- 向OHNativeWindow申请一块buffer, 并获取这块buffer的handle,然后映射内存;
- 创建画布Canvas, 将bitmap和画布绑定;
- 使用Canvas相关api绘制内容;
- 将bitmap转换成像素数据,并通过之前映射的buffer句柄,将bitmap数据写到buffer中;
- 将内容放回到Buffer队列,在下次Vsync信号就会将buffer中的内容绘制到屏幕上;
- 取消映射内存;
7.ArkTS侧使用XComponent
- 添加so依赖
"devDependencies": {
"@types/libnativerender.so": "file:./src/main/cpp/types/libnativerender"
}
- 定义native接口
export default interface XComponentContext {
draw(minuteData: UPMarketMinuteData[], length: number): void;
};
- 使用XComponent并获取XComponentContext, 通过它可以调用native层函数
XComponent({
id: 'xcomponentId',
type: 'surface',
libraryname: 'nativerender'
})
.onLoad((xComponentContext) => {
if (xComponentContext) {
this.xComponentContext = xComponentContext as XComponentContext;
}
})
.width('100%')
.height(600)
.backgroundColor(Color.Gray)
- 调用native函数绘制分时图
this.monitor.subscribeRTMinuteData(this.TAG_REQUEST_MINUTE, param, (rsp) => {
if (rsp.isSuccessful() && rsp.result != null && rsp.result.length > 0 && this.xComponentContext) {
this.xComponentContext.draw(rsp.result!, rsp.result.length)
}
})