Advertisement

Simulating Cursor For Textbox In SDL2

Started by May 23, 2018 09:19 AM
1 comment, last by 3dmodelerguy 6 years, 8 months ago

So I have this code to create a textbox ui element with SDL2 and for the most part it works:


#include <iostream>

#include "TextboxUi.hpp"
#include "../Engine/Text.hpp";
#include "../Utility/SdlUtility.hpp";
#include "../Engine/Game.hpp";

TextboxUi::TextboxUi(int x, int y, int width, int height, SDL_Color backgroundColor, SDL_Color textColor) {
  _background = {x, y, width, height};
  _backgroundColor = backgroundColor;
  _textColor = textColor;
}

void TextboxUi::setValue(std::string value) {
  _value = value;
}

void TextboxUi::handleInput(SDL_Event &event) {
  switch (event.type) {
    case SDL_TEXTINPUT: {
      if (_isActive) {
        _value += event.text.text;
        _cursorPosition += 1;
      }

      break;
    }

    case SDL_TEXTEDITING: {
      break;
    }

    case SDL_KEYUP: {
      switch (event.key.keysym.sym) {
      case SDLK_BACKSPACE:
        if (_value.size() == 0) {
          break;
        }

        _cursorPosition -= 1;
        _value.erase(_cursorPosition, 1);

        break;

      case SDLK_s: {
        if (!_isActive) {
          _isActive = true;
        }

        break;
      }

      case SDLK_LEFT: {
        if (_cursorPosition == 0) {
          break;
        }

        _cursorPosition -= 1;

        break;
      }

      case SDLK_RIGHT: {
        if (_cursorPosition == _value.size()) {
          break;
        }

        _cursorPosition += 1;

        break;
      }

      case SDLK_ESCAPE:
        _isActive = false;
        _value = "";

        break;

      default:
        break;
      }

      break;
    }

    default:
      break;
  }
}

void TextboxUi::enable() {
  _isActive = true;
}

void TextboxUi::disable() {
  _isActive = false;
}

void TextboxUi::draw(SDL_Renderer* renderer) {
  SdlUtility::setRenderDrawColor(Game::renderer, _backgroundColor);
  SDL_RenderFillRect(Game::renderer, &_background);

  // if there is no text Text would fail to create the surface and texture (not quite sure why)
  if (_value.size() == 0) {
    return;
  }

  Text text = Text("Assets/Fonts/Vera.ttf", 12, _value, _textColor);
  text.display(_background.x + 5, _background.y + 2);

  // @todo implement visual for text cursor
}

The one last thing I want to do before I call this textbox done for the time being is try to figure out how to simulate a cursor. At this point just getting a solid cursor would be final (though ultimately I would like to have it blinking. I have the cursor position so I know between which characters the cursor should be however I am not sure how to calculate that.

Is there a way to calculate the width of a given string without actually rendering said sting to the screen with SDL2 / SDL2_ttf?

I'm an idiot (ie. I can't use google well), finally found out about `TTF_SizeText()`.

This topic is closed to new replies.

Advertisement