GProgressBar.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include <LibGUI/GProgressBar.h>
  2. #include <SharedGraphics/Painter.h>
  3. GProgressBar::GProgressBar(GWidget* parent)
  4. : GWidget(parent)
  5. {
  6. start_timer(10);
  7. }
  8. GProgressBar::~GProgressBar()
  9. {
  10. }
  11. void GProgressBar::set_value(int value)
  12. {
  13. if (m_value == value)
  14. return;
  15. m_value = value;
  16. update();
  17. }
  18. void GProgressBar::set_range(int min, int max)
  19. {
  20. ASSERT(min < max);
  21. m_min = min;
  22. m_max = max;
  23. if (m_value > m_max)
  24. m_value = m_max;
  25. if (m_value < m_min)
  26. m_value = m_min;
  27. }
  28. void GProgressBar::paint_event(GPaintEvent& event)
  29. {
  30. Painter painter(*this);
  31. painter.set_clip_rect(event.rect());
  32. // First we fill the entire widget with the gradient. This incurs a bit of
  33. // overdraw but ensures a consistent look throughout the progression.
  34. Color start_color(110, 34, 9);
  35. Color end_color(244, 202, 158);
  36. painter.fill_rect_with_gradient(rect(), start_color, end_color);
  37. float range_size = m_max - m_min;
  38. float progress = (m_value - m_min) / range_size;
  39. // Then we draw the progress text over the gradient.
  40. // We draw it twice, once offset (1, 1) for a drop shadow look.
  41. auto progress_text = String::format("%d%%", (int)(progress * 100));
  42. painter.draw_text(rect().translated(1, 1), progress_text, TextAlignment::Center, Color::Black);
  43. painter.draw_text(rect(), progress_text, TextAlignment::Center, Color::White);
  44. // Then we carve out a hole in the remaining part of the widget.
  45. // We draw the text a third time, clipped and inverse, for sharp contrast.
  46. painter.save();
  47. float progress_width = progress * width();
  48. Rect hole_rect { (int)progress_width, 0, (int)(width() - progress_width), height() };
  49. painter.set_clip_rect(hole_rect);
  50. painter.fill_rect(hole_rect, Color::White);
  51. painter.draw_text(rect().translated(0, 0), progress_text, TextAlignment::Center, Color::Black);
  52. painter.restore();
  53. // Finally, draw a frame around the widget.
  54. painter.draw_rect(rect(), Color::Black);
  55. }