SDL2窗口调整鼠标位置

时间:2014-07-12 18:59:40

标签: resize window position mouse sdl-2

当我在SDL2中调整窗口大小并使用SDL_RenderSetLogicalSize时,如何使位置适应新窗口位置?

我希望能够将文本悬停并使其改变颜色,但每当我调整窗口大小时,它仍然在相同的窗口中。有没有办法改编鼠标?

void MainMenu::CheckHover()
{
    for (std::list<MenuItem>::iterator it = menuItems.begin(); it != menuItems.end(); it++)
    {
        Text* text = (*it).text;
        float Left = text->GetX();
        float Right = text->GetX() + text->GetWidth();
        float Top = text->GetY();
        float Bottom = text->GetY() + text->GetHeight();

        if (mouseX < Left ||
            mouseX > Right ||
            mouseY < Top ||
            mouseY > Bottom)
        {
            //hover = false
            text->SetTextColor(255, 255, 255);
        }
        else
        {
            //hover = true
            text->SetTextColor(100, 100, 100);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

前段时间我遇到了类似的问题,这是由于我在一个SDL事件循环中多次更新鼠标位置。我想通过拖动鼠标来移动SDL_Texture,但是在调整大小后它失败了,因为不知何故鼠标坐标搞砸了。

我所做的是重新安排我的代码,只有一个事件处理鼠标位置更新。此外,我没有使用任何SDL_SetWindowSize()调用。当用户调整窗口大小时,由于SDL_RenderSetLogicalSize(),渲染器会被适当调整大小。

相关的代码部分看起来像这样 - 有些东西适合你的情况。我还建议使用SDL_Rect来检测鼠标是否在文本区域内,因为如果窗口/渲染器改变大小,SDL_Rects将在内部调整大小。

  //Declarations
  //...
  SDL_Point mousePosRunning;

  // Picture in picture texture I wanted to move
  SDL_Rect  pipRect;

  // Init resizable sdl window
  window = SDL_CreateWindow(
     "Window",
     SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex),
     SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex),
     defaultW, defaultH,
     SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
  renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
  SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");    // This one is optional
  SDL_RenderSetLogicalSize(renderer, defaultW, defaultH);

  // SDL main loop
  while(SDL_PollEvent(&event) && running)
  {
     switch (event.type)
     {
      // Some event handling here
      // ...
      // Handle mouse motion event
      case SDL_MOUSEMOTION:
           // Update mouse pos
           mousePosRunning.x = event.button.x;
           mousePosRunning.y = event.button.y;

           // Check if mouse is inside the pip region
           if (SDL_EnclosePoints(&mousePosRunning, 1, &pipRect, NULL))
           {
              // Mouse is inside the pipRect
              // do some stuff... i.e. change color
           }
           else
           {
              // Mouse left rectangle 
           }
           break;
     }
  }
相关问题