@@ -356,41 +356,47 @@ BitmapFont::wrap_to_width(const std::string& s_, float width, std::string* overf
356356}
357357
358358
359- void
359+ Rectf
360360BitmapFont::draw_text (Canvas& canvas, const std::string& text,
361- const Vector& pos_ , FontAlignment alignment, int layer, const Color& color)
361+ const Vector& pos , FontAlignment alignment, int layer, const Color& color)
362362{
363- float x = pos_.x ;
364- float y = pos_.y ;
363+ float min_x = pos.x ;
364+ float last_y = pos.y ;
365+ float max_width = 0 .f ;
365366
366367 std::string::size_type last = 0 ;
367- for (std::string::size_type i = 0 ;; ++i)
368+ for (std::string::size_type i = 0 ; i <= text. size () ; ++i)
368369 {
369- if (text[i] == ' \n ' || i == text.size ())
370- {
371- std::string temp = text.substr (last, i - last);
370+ if (i != text.size () && text[i] != ' \n ' )
371+ continue ;
372372
373- // Calculate X positions based on the alignment type.
374- Vector pos = Vector (x, y );
373+ const std::string temp = text. substr (last, i - last);
374+ const float width = get_text_width (temp );
375375
376- if (alignment == ALIGN_CENTER)
377- pos.x -= get_text_width (temp) / 2 ;
378- else if (alignment == ALIGN_RIGHT)
379- pos.x -= get_text_width (temp);
376+ // Calculate X positions based on the alignment type.
377+ Vector new_pos = Vector (pos.x , last_y);
380378
381- // Cast font position to integer to get a clean drawing result and
382- // no blurring as we would get with subpixel positions.
383- pos.x = std::truncf (pos.x );
379+ if (alignment == ALIGN_CENTER)
380+ new_pos.x -= width / 2 .0f ;
381+ else if (alignment == ALIGN_RIGHT)
382+ new_pos.x -= width;
384383
385- draw_text (canvas, temp, pos, layer, color);
384+ // Cast font position to integer to get a clean drawing result and
385+ // no blurring as we would get with subpixel positions.
386+ new_pos.x = std::truncf (new_pos.x );
386387
387- if (i == text.size ())
388- break ;
388+ if (new_pos.x < min_x)
389+ min_x = new_pos.x ;
390+ if (width > max_width)
391+ max_width = width;
389392
390- y += static_cast <float >(char_height) + 2 .0f ;
391- last = i + 1 ;
392- }
393+ draw_text (canvas, temp, new_pos, layer, color);
394+
395+ last_y += static_cast <float >(char_height) + 2 .0f ;
396+ last = i + 1 ;
393397 }
398+
399+ return Rectf (min_x, pos.y , min_x + max_width, last_y);
394400}
395401
396402void
0 commit comments