Text.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /*
  2. GWEN
  3. Copyright (c) 2010 Facepunch Studios
  4. See license in Gwen.h
  5. */
  6. #include "Gwen/Gwen.h"
  7. #include "Gwen/Controls/Text.h"
  8. #include "Gwen/Skin.h"
  9. #include "Gwen/Utility.h"
  10. using namespace Gwen;
  11. using namespace Gwen::ControlsInternal;
  12. GWEN_CONTROL_CONSTRUCTOR( Text )
  13. {
  14. m_Font = NULL;
  15. m_Color = Gwen::Colors::Black; // TODO: From skin somehow..
  16. SetMouseInputEnabled( false );
  17. }
  18. Text::~Text()
  19. {
  20. // NOTE: This font doesn't need to be released
  21. // Because it's a pointer to another font somewhere.
  22. }
  23. void Text::RefreshSize()
  24. {
  25. if ( !GetFont() )
  26. {
  27. Debug::AssertCheck( 0, "Text::RefreshSize() - No Font!!\n" );
  28. return;
  29. }
  30. Gwen::Point p( 1, GetFont()->size );
  31. if ( Length() > 0 )
  32. {
  33. p = GetSkin()->GetRender()->MeasureText( GetFont(), m_String );
  34. }
  35. if ( p.x == Width() && p.y == Height() )
  36. return;
  37. SetSize( p.x, p.y );
  38. InvalidateParent();
  39. Invalidate();
  40. }
  41. Gwen::Font* Text::GetFont()
  42. {
  43. return m_Font;
  44. }
  45. void Text::SetString( const UnicodeString& str ){ m_String = str; Invalidate(); }
  46. void Text::SetString( const String& str ){ SetString( Gwen::Utility::StringToUnicode( str ) ); }
  47. void Text::Render( Skin::Base* skin )
  48. {
  49. if ( Length() == 0 || !GetFont() ) return;
  50. skin->GetRender()->SetDrawColor( m_Color );
  51. skin->GetRender()->RenderText( GetFont(), Gwen::Point( 0, 0 ), m_String );
  52. }
  53. void Text::Layout( Skin::Base* /*skin*/ )
  54. {
  55. RefreshSize();
  56. }
  57. Gwen::Point Text::GetCharacterPosition( int iChar )
  58. {
  59. if ( Length() == 0 || iChar == 0 )
  60. {
  61. return Gwen::Point( 1, 0 );
  62. }
  63. UnicodeString sub = m_String.substr( 0, iChar );
  64. Gwen::Point p = GetSkin()->GetRender()->MeasureText( GetFont(), sub );
  65. if ( p.y >= m_Font->size )
  66. p.y -= m_Font->size;
  67. return p;
  68. }
  69. int Text::GetClosestCharacter( Gwen::Point p )
  70. {
  71. int iDistance = 4096;
  72. int iChar = 0;
  73. for ( size_t i=0; i<m_String.length()+1; i++ )
  74. {
  75. Gwen::Point cp = GetCharacterPosition( i );
  76. int iDist = abs(cp.x - p.x) + abs(cp.y - p.y); // this isn't proper
  77. if ( iDist > iDistance ) continue;
  78. iDistance = iDist;
  79. iChar = i;
  80. }
  81. return iChar;
  82. }
  83. void Text::OnScaleChanged()
  84. {
  85. Invalidate();
  86. }