Aqoole_Hateenaの技術日記

vulkan+raytraceで色々描いてます

Android NDKを用いたC++でのtouch位置取得方法

android_main()でコールバック関数の登録

android_appにinput eventが通知された際に呼び出されるコールバック関数を登録する。

int32_t handle_input(struct android_app* app, AInputEvent* inputEvent)
{
  //define app process
}

void android_main(struct android_app* app) {
:
:
  // Set the callback to process system events
  app->onInputEvent = handle_input;
:
:
}

eventの取得

コールバック関数の中にて、android/input.hに定義されている関数を用いてeventを取得する。
例:

int32_t AInputEvent_getType(const AInputEvent* event);

int32_t AInputEvent_getDeviceId(const AInputEvent* event);

int32_t AInputEvent_getSource(const AInputEvent* event);

各関数で取得できる値の説明はandroid公式に書かれている。
Input  |  Android NDK  |  Android Developers

touchしたx座標、y座標を取得する具体例

float touchPosition[2] = {0.0f, 0.0f};

int32_t handle_input(struct android_app* app, AInputEvent* inputEvent)
{
  int32_t eventType = AInputEvent_getType(inputEvent);
  switch (eventType)
  {
      case AINPUT_EVENT_TYPE_KEY :
        break;
      case AINPUT_EVENT_TYPE_MOTION :
        touchPosition[0] = AMotionEvent_getX(inputEvent, 0);
        touchPosition[1] = AMotionEvent_getY(inputEvent, 0);
        break;
      case AINPUT_EVENT_TYPE_FOCUS :
        break;
  }
  return 0;
}

void android_main(struct android_app* app) {
  app->onInputEvent = handle_input;
  :
  :
  // Main loop
  do {
       :
       :
        userFunction(touchPosition);
       :
       :
    }
  } while (app->destroyRequested == 0);
}

座標系

getX, getYで取得できる数値は、以下のようなウィンドウ左上を原点とする座標系のピクセル位置である。

f:id:Aqoole_Hateena:20211226213352p:plain
座標系