移植 AWTK 到 纯血鸿蒙 (HarmonyOS NEXT) 系统 (6) - 触屏事件

AWTK 作为一个GUI引擎,自然少不了对触屏事件的支持。这里我们先支持单点触摸,后续再支持多点手势。

1. 注册 XComponent 的触屏事件回调

这个在 AppNapi 的构造函数中完成:

cpp 复制代码
AppNapi::AppNapi(std::string &id) {
    id_ = id;
    component_ = nullptr;
    auto appCallback = AppNapi::GetNXComponentCallback();
    appCallback->OnSurfaceCreated = OnSurfaceCreatedCB;
    appCallback->OnSurfaceChanged = OnSurfaceChangedCB;
    appCallback->OnSurfaceDestroyed = OnSurfaceDestroyedCB;
    appCallback->DispatchTouchEvent = DispatchTouchEventCB;
    auto appMouseEventCallback = AppNapi::GetNXComponentMouseEventCallback();
    appMouseEventCallback->DispatchMouseEvent = DispatchMouseEventCB;

    awtk_app_ = new AwtkApp(id);
}

2. 在触屏事件的回调函数中,将事件分发给 awtk_app

事件需要根据当前屏幕的缩放比例,转换为 awtk 的坐标系。

cpp 复制代码
void AppNapi::DispatchTouchEvent(OH_NativeXComponent *component, void *window) {
    int32_t ret = OH_NativeXComponent_GetTouchEvent(component, window, &touchEvent_);
    if (ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
        double dpr = awtk_app_->GetDevicePixelRatio();
        int x = touchEvent_.x / dpr;
        int y = touchEvent_.y / dpr;
        int button = 0;

        switch (touchEvent_.type) {
        case OH_NATIVEXCOMPONENT_DOWN: {
            awtk_app_->DispatchPointerDown(button, x, y);
            break;
        }
        case OH_NATIVEXCOMPONENT_MOVE: {
            awtk_app_->DispatchPointerMove(button, x, y);
            break;
        }
        case OH_NATIVEXCOMPONENT_UP: {
            awtk_app_->DispatchPointerUp(button, x, y);
            break;
        }
        default: {
            break;
        }
        }
    } else {
        LOGE("Touch fail");
    }
}

3. 将事件注入主循环

cpp 复制代码
void AwtkApp::DispatchPointerDown(int button, int x, int y) {
    mPressed = true;

    pointer_event_t event;
    widget_t *widget = window_manager();
    pointer_event_init(&event, EVT_POINTER_DOWN, widget, x, y);
    event.pressed = mPressed;
    event.button = button;

    event_queue_req_t r;
    memset(&r, 0x00, sizeof(r));
    r.pointer_event = event;
    main_loop_queue_event(main_loop(), &r);
}

4. 加入触屏事件支持后,就可以通过触屏操作界面了

相关推荐
BoomHe3 小时前
Now in Android 架构模式全面分析
android·android jetpack
Hcourage4 小时前
鸿蒙工程获取C/C++代码覆盖
harmonyos
二流小码农10 小时前
鸿蒙开发:上传一张参考图片便可实现页面功能
android·ios·harmonyos
鹏程十八少10 小时前
4.Android 30分钟手写一个简单版shadow, 从零理解shadow插件化零反射插件化原理
android·前端·面试
Kapaseker11 小时前
一杯美式搞定 Kotlin 空安全
android·kotlin
三少爷的鞋11 小时前
Android 协程时代,Handler 应该退休了吗?
android
万少20 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
火柴就是我1 天前
让我们实现一个更好看的内部阴影按钮
android·flutter
砖厂小工1 天前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github
张拭心1 天前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能