Selection.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Selection.h"
  7. #include "ImageEditor.h"
  8. #include <LibGfx/Painter.h>
  9. namespace PixelPaint {
  10. constexpr int marching_ant_length = 4;
  11. void Selection::paint(Gfx::Painter& painter, ImageEditor const& editor)
  12. {
  13. draw_marching_ants(painter, editor.image_rect_to_editor_rect(m_rect).to_type<int>());
  14. }
  15. Selection::Selection(ImageEditor& editor)
  16. : m_editor(editor)
  17. {
  18. m_marching_ants_timer = Core::Timer::create_repeating(80, [this] {
  19. ++m_marching_ants_offset;
  20. m_marching_ants_offset %= marching_ant_length;
  21. if (!is_empty())
  22. m_editor.update();
  23. });
  24. m_marching_ants_timer->start();
  25. }
  26. void Selection::draw_marching_ants(Gfx::Painter& painter, Gfx::IntRect const& rect) const
  27. {
  28. int offset = m_marching_ants_offset;
  29. auto draw_pixel = [&](int x, int y) {
  30. if ((offset % marching_ant_length) != 0)
  31. painter.set_pixel(x, y, Color::Black);
  32. offset++;
  33. };
  34. // Top line
  35. for (int x = rect.left(); x <= rect.right(); ++x)
  36. draw_pixel(x, rect.top());
  37. // Right line
  38. for (int y = rect.top() + 1; y <= rect.bottom(); ++y)
  39. draw_pixel(rect.right(), y);
  40. // Bottom line
  41. for (int x = rect.right() - 1; x >= rect.left(); --x)
  42. draw_pixel(x, rect.bottom());
  43. // Left line
  44. for (int y = rect.bottom() - 1; y > rect.top(); --y)
  45. draw_pixel(rect.left(), y);
  46. }
  47. }