鸿蒙开发5.0【基于Drawing的图形/文字绘制及双缓冲模拟实现刷新】

场景描述

[Native Drawing]模块提供了一系列的接口用于基本图形和字体的绘制。

Drawing绘制的内容无法直接在屏幕上显示,需要借用[XComponent]以及[Native Window]的能力支持,将绘制的内容通过Native Window送显。这里介绍如何使用Drawing绘制内容,然后通过NativeWindow贴图到XComponent的双缓冲实现。

双缓冲实现刷新:

  1. 在内存中创建一片内存区域,把将要绘制的图片预先绘制到内存中,在绘制显示的时候直接获取缓冲区的图片进行绘制。更具体一点来说:先通过Drawing方法将要绘制的所有的图形绘制到一个Bitmap上也就是先在内存空间完成,然后获取位图的像素地址、并将其拷贝到XComponent的NativeWindow地址。完成贴图,将图片显示在屏幕上。
  2. 启用双缓冲后,所有画图操作会首先呈现到内存缓冲而不是屏幕上的绘图图面。 所有画图操作完成后,内存缓冲会直接复制到与之关联的绘图图面。 由于屏幕上仅执行一个图形操作,因此与复杂画图操作相关的图像闪烁可得以消除。
  3. 很多图形的操作都很复杂需要大量的计算,很难访问一次显示缓冲区就能写入待显示的完整图形数据,通常需要多次访问显示缓冲区,每次访问时写入最新计算的图形数据。而这样造成的后果是一个需要复杂计算的图形,你看到的效果可能是一部分一部分地显示出来的,造成很大的闪烁不连贯。而使用双缓冲,可以使你先将计算的中间结果存放在另一个缓冲区中,待全部的计算结束,该缓冲区已经存储了完整的图形之后,再将该缓冲区的图形数据一次性复制到显示缓冲区。

方案描述

一.图形绘制:

1.使用Drawing进行图形绘制与显示时,需要使用Native Drawing模块的画布画笔绘制一个基本的2D图形;

2.将图形内容写入Native Window提供的图形Buffer,将Buffer提交到图形队列;

3.再利用XComponent将C++代码层与ArkTS层对接,实现在ArkTS层调用绘制和显示的逻辑,最终在应用上显示图形。

二.文本绘制:

Native Drawing模块关于文本绘制提供两类API接口

一类是具有定制排版能力的接口:如OH_Drawing_Typography,OH_Drawing_TypographyStyle,OH_Drawing_TextStyle等类型。支撑用户设置排版风格和文本风格,可调用OH_Drawing_TypographyHandlerAddText添加文本并调用OH_Drawing_TypographyLayout和OH_Drawing_TypographyPaint对文本进行排版和绘制。

另一类是不具有定制排版能力的接口:如OH_Drawing_Font,OH_Drawing_TextBlob,OH_Drawing_RunBuffer等类型。支撑具备自排版能力的用户将排版结果构造为OH_Drawing_TextBlob并调用OH_Drawing_CanvasDrawTextBlob绘制OH_Drawing_TextBlob描述的文本块。

场景实现

添加开发依赖

CMakeLists.txt中添加以下lib。

libace_napi.z.so
libace_ndk.z.so
libnative_window.so
libnative_drawing.so

使用XComponent构建绘制环境

1.使用XComponent组件

build() {
  Column() {
    Row() {
      XComponent({ id: 'xcomponentId', type: 'surface', libraryname: 'entry' })
        .onLoad((xComponentContext) => {
          this.xComponentContext = xComponentContext as XComponentContext;
        }).width('640px') // 64的倍数
    }.height('100%')
  }
}

2.在 Native C++层获取NativeXComponent与ts侧XComponent关联。此步骤需要在napi_init的过程中处理。创建一个PluginManger单例类,用于管理NativeXComponent。

class PluginManager {
  public:
  ~PluginManager();

  static PluginManager *GetInstance();

  void SetNativeXComponent(std::string &id, OH_NativeXComponent *nativeXComponent);
  SampleBitMap *GetRender(std::string &id);
  void Export(napi_env env, napi_value exports);
  private:

    std::unordered_map<std::string, OH_NativeXComponent *> nativeXComponentMap_;
  std::unordered_map<std::string, SampleBitMap *> pluginRenderMap_;
};
void PluginManager::Export(napi_env env, napi_value exports) {
  if ((env == nullptr) || (exports == nullptr)) {
    DRAWING_LOGE("Export: env or exports is null");
    return;
  }

  napi_value exportInstance = nullptr;
  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;
  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;
  }

  std::string id(idStr);
  auto context = PluginManager::GetInstance();
  if ((context != nullptr) && (nativeXComponent != nullptr)) {
    context->SetNativeXComponent(id, nativeXComponent);
    auto render = context->GetRender(id);
    if (render != nullptr) {
      render->RegisterCallback(nativeXComponent);
      render->Export(env, exports);
    } else {
      DRAWING_LOGE("render is nullptr");
    }
  }
}

3.注册回调函数。通过[OnSurfaceCreated]回调函数获取Native Window.

// 定义回调函数
void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window)
{
  // 可获取 OHNativeWindow 实例
  OHNativeWindow* nativeWindow = static_cast<OHNativeWindow*>(window);
  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 = SampleBitMap::GetInstance(id);
  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);
    DRAWING_LOGI("xComponent width = %{public}llu, height = %{public}llu", width, height);
  }
}

场景一:使用drawing进行文本绘制

方案一:定制排版绘制

1.创建画布和bitmap实例。

// 创建bitmap
cBitmap_ = OH_Drawing_BitmapCreate();
OH_Drawing_BitmapFormat cFormat {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUE};
//描述位图像素颜色类型和透明度
// width的值必须为bufferHandle->stride / 4
OH_Drawing_BitmapBuild(cBitmap_, width_, height_, &cFormat);
//初始化宽高,将上面的格式设置进去
// 创建canvas
cCanvas_ = OH_Drawing_CanvasCreate();
OH_Drawing_CanvasBind(cCanvas_, cBitmap_);
//将上面位图对象和画布绑定
OH_Drawing_CanvasClear(cCanvas_, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0xFF, 0xFF));
//将画布清空

2.设置排版

// 选择排版属性
OH_Drawing_TypographyStyle* typoStyle = OH_Drawing_CreateTypographyStyle();
OH_Drawing_SetTypographyTextDirection(typoStyle, TEXT_DIRECTION_LTR);
//目前提供从左往右和右往左两种
OH_Drawing_SetTypographyTextAlign(typoStyle, TEXT_ALIGN_LEFT);
//对齐方式

3.设置文本风格。

// 设置文字颜色
OH_Drawing_TextStyle* txtStyle = OH_Drawing_CreateTextStyle();
OH_Drawing_SetTextStyleColor(txtStyle, OH_Drawing_ColorSetArgb(0xFF, 0x00, 0x00, 0x00));
// 设置文字大小、字重等属性
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);
OH_Drawing_FontCollection* fontCollection = OH_Drawing_CreateFontCollection();
// 注册自定义字体
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);

4.生成文本内容效果 通过OH_Drawing_TypographyHandlerAddText设置文本内容 OH_Drawing_TypographyLayout设置排版布局

OH_Drawing_TypographyCreate *handler =
  OH_Drawing_CreateTypographyHandler(typoStyle, OH_Drawing_CreateFontCollection());
OH_Drawing_TypographyHandlerPushTextStyle(handler, txtStyle);
// 设置文字内容
const char *text = "填写你想要的文本内容\n";
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] = {width_ / 5.0, height_ / 2.0};
// 将文本绘制到画布上
OH_Drawing_TypographyPaint(typography, cCanvas_, position[0], position[1]);

5.效果图

5

场景二:使用drawing进行图形的绘制

1.创建Bitmap和画布实例(同上)

2.构造Path形状

void SampleBitMap::ConstructPath()
{
  int len = height_ / 4;
  float aX = width_ / 2;
  float aY = height_ / 4;
  float dX = aX - len * std::sin(18.0f);
  float dY = aY + len * std::cos(18.0f);
  float cX = aX + len * std::sin(18.0f);
  float cY = dY;
  float bX = aX + (len / 2.0);
  float bY = aY + std::sqrt((cX - dX) * (cX - dX) + (len / 2.0) * (len / 2.0));
  float eX = aX - (len / 2.0);
  float eY = bY;
  // 创建一个path对象,然后使用接口连接成一个五角星形状
  cPath_ = OH_Drawing_PathCreate();
  // 指定path的起始位置
  OH_Drawing_PathMoveTo(cPath_, aX, aY);
  // 用直线连接到目标点
  OH_Drawing_PathLineTo(cPath_, bX, bY);
  OH_Drawing_PathLineTo(cPath_, cX, cY);
  OH_Drawing_PathLineTo(cPath_, dX, dY);
  OH_Drawing_PathLineTo(cPath_, eX, eY);
  // 闭合形状,path绘制完毕
  OH_Drawing_PathClose(cPath_);
}

3.设置画笔和画刷样式。

void SampleBitMap::SetPenAndBrush()
{
  constexpr float penWidth = 10.0f; // pen width 10
  // 创建一个画笔Pen对象,Pen对象用于形状的边框线绘制
  cPen_ = OH_Drawing_PenCreate();
  OH_Drawing_PenSetAntiAlias(cPen_, true);
  OH_Drawing_PenSetColor(cPen_, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0x00, 0x00));
  OH_Drawing_PenSetWidth(cPen_, penWidth);
  OH_Drawing_PenSetJoin(cPen_, LINE_ROUND_JOIN);
  // 将Pen画笔设置到canvas中
  OH_Drawing_CanvasAttachPen(cCanvas_, cPen_);

  // 创建一个画刷Brush对象,Brush对象用于形状的填充
  cBrush_ = OH_Drawing_BrushCreate();
  OH_Drawing_BrushSetColor(cBrush_, OH_Drawing_ColorSetArgb(0xFF, 0x00, 0xFF, 0x00));

  // 将Brush画刷设置到canvas中
  OH_Drawing_CanvasAttachBrush(cCanvas_, cBrush_);
}

4.绘制图形

void SampleBitMap::DrawPath()
{
  // 在画布上画path的形状,五角星的边框样式为pen设置,颜色填充为Brush设置
  OH_Drawing_CanvasDrawPath(cCanvas_, cPath_);
}

绘制内容送显的双缓冲实现

这里要实现双缓冲刷新这里需要将前面绘制到Bitmap内存空间上的像素地址拷贝到Native Window上,完成贴图。

1.通过前面OnSurfaceCreatedCB回调保存的Native Window来申请Native Window Buffer。

// 通过 OH_NativeWindow_NativeWindowRequestBuffer 获取 OHNativeWindowBuffer 实例
int32_t ret = OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow_, &buffer_, &fenceFd_);

2.通过[OH_NativeWindow_GetBufferHandleFromNative]获取bufferHandle。

bufferHandle_ = OH_NativeWindow_GetBufferHandleFromNative(buffer_);

3.使用mmap接口拿到bufferHandle的内存虚拟地址。

mappedAddr_ = static_cast<uint32_t *>(
  // 使用内存映射函数mmap将bufferHandle对应的共享内存映射到用户空间,可以通过映射出来的虚拟地址向bufferHandle中写入图像数据
  // bufferHandle->virAddr是bufferHandle在共享内存中的起始地址,bufferHandle->size是bufferHandle在共享内存中的内存占用大小
mmap(bufferHandle_->virAddr, bufferHandle_->size, PROT_READ | PROT_WRITE, MAP_SHARED, bufferHandle_->fd, 0));
if (mappedAddr_ == MAP_FAILED) {
  DRAWING_LOGE("mmap failed");
}

4.使用[drawing_bitmap.h]的[OH_Drawing_BitmapGetPixels]接口获取到画布绑定bitmap实例的像素地址,该地址指向的内存包含画布刚刚绘制的像素数据。将绘制内容填充到申请的Native Window Buffer中。

// 画完后获取像素地址,地址指向的内存包含画布画的像素数据
void *bitmapAddr = OH_Drawing_BitmapGetPixels(cBitmap_);
uint32_t *value = static_cast<uint32_t *>(bitmapAddr);

// 使用mmap获取到的地址来访问内存
uint32_t *pixel = static_cast<uint32_t *>(mappedAddr_);
for (uint32_t x = 0; x < width_; x++) {
  for (uint32_t y = 0; y < height_; y++) {
    *pixel++ = *value++;
  }
}

5.设置刷新区域,送显。

// 如果Region中的Rect为nullptr,或者rectNumber为0,则认为OHNativeWindowBuffer全部有内容更改。
Region region {nullptr, 0};
// 通过OH_NativeWindow_NativeWindowFlushBuffer 提交给消费者使用,例如:显示在屏幕上。
OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer_, fenceFd_, region);

6.释放内存

// 去掉内存映射
int result = munmap(mappedAddr_, bufferHandle_->size);
if (result == -1) {
  DRAWING_LOGE("munmap failed!");
}
// 销毁创建的对象
OH_Drawing_BrushDestroy(cBrush_);
cBrush_ = nullptr;
OH_Drawing_PenDestroy(cPen_);
cPen_ = nullptr;
OH_Drawing_PathDestroy(cPath_);
cPath_ = nullptr;
OH_Drawing_CanvasDestroy(cCanvas_);
cCanvas_ = nullptr;
OH_Drawing_BitmapDestroy(cBitmap_);
cBitmap_ = nullptr;
void OnSurfaceDestroyedCB(OH_NativeXComponent *component, void *window) {
  DRAWING_LOGI("OnSurfaceDestroyedCB");
  if ((component == nullptr) || (window == nullptr)) {
    DRAWING_LOGE("OnSurfaceDestroyedCB: 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("OnSurfaceDestroyedCB: Unable to get XComponent id");
    return;
  }
  std::string id(idStr);
  SampleBitMap::Release(id);
}

TS调用绘制接口

@Entry
@Component
struct Index {
  private xComponentContext: XComponentContext | undefined = undefined;

  build() {
    Column() {
      Row() {
        XComponent({ id: 'xcomponentId', type: 'surface', libraryname: 'entry' })
          .onLoad((xComponentContext) => {
            this.xComponentContext = xComponentContext as XComponentContext;
          }).width('960px') // Multiples of 64
      }.height('88%')
      Row() {
        Button('Draw Path')
          .fontSize('16fp')
          .fontWeight(500)
          .margin({ bottom: 24, right: 12 })
          .onClick(() => {
            console.log(TAG, "Draw Path click");
            if (this.xComponentContext) {
              console.log(TAG, "Draw Path");
              this.xComponentContext.drawPattern();
            }
          })
          .width('33.6%')
          .height(40)
          .shadow(ShadowStyle.OUTER_DEFAULT_LG)
        Button('Draw Text')
          .fontSize('16fp')
          .fontWeight(500)
          .margin({ bottom: 24, left: 12 })
          .onClick(() => {
            console.log(TAG, "draw text click");
            if (this.xComponentContext) {
              console.log(TAG, "draw text");
              this.xComponentContext.drawText();
            }
          })
          .width('33.6%')
          .height(40)
          .shadow(ShadowStyle.OUTER_DEFAULT_LG)
      }
      .width('100%')
      .justifyContent(FlexAlign.Center)
      .shadow(ShadowStyle.OUTER_DEFAULT_SM)
      .alignItems(VerticalAlign.Bottom)
      .layoutWeight(1)
    }
  }
}

以上就是本篇文章所带来的鸿蒙开发中一小部分技术讲解;想要学习完整的鸿蒙全栈技术。可以在结尾找我可全部拿到!
下面是鸿蒙的完整学习路线,展示如下:
1

除此之外,根据这个学习鸿蒙全栈学习路线,也附带一整套完整的学习【文档+视频】,内容包含如下

内容包含了:(ArkTS、ArkUI、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、鸿蒙南向开发、鸿蒙项目实战)等技术知识点。帮助大家在学习鸿蒙路上快速成长!

鸿蒙【北向应用开发+南向系统层开发】文档

鸿蒙【基础+实战项目】视频

鸿蒙面经

2

为了避免大家在学习过程中产生更多的时间成本,对比我把以上内容全部放在了↓↓↓想要的可以自拿喔!谢谢大家观看!
3

  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值