ImagePaintable.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibGfx/StylePainter.h>
  7. #include <LibWeb/HTML/HTMLImageElement.h>
  8. #include <LibWeb/Layout/ImageBox.h>
  9. #include <LibWeb/Painting/BorderRadiusCornerClipper.h>
  10. #include <LibWeb/Painting/ImagePaintable.h>
  11. namespace Web::Painting {
  12. NonnullRefPtr<ImagePaintable> ImagePaintable::create(Layout::ImageBox const& layout_box)
  13. {
  14. return adopt_ref(*new ImagePaintable(layout_box));
  15. }
  16. ImagePaintable::ImagePaintable(Layout::ImageBox const& layout_box)
  17. : PaintableBox(layout_box)
  18. {
  19. }
  20. Layout::ImageBox const& ImagePaintable::layout_box() const
  21. {
  22. return static_cast<Layout::ImageBox const&>(layout_node());
  23. }
  24. void ImagePaintable::paint(PaintContext& context, PaintPhase phase) const
  25. {
  26. if (!is_visible())
  27. return;
  28. // FIXME: This should be done at a different level. Also rect() does not include padding etc!
  29. if (!context.viewport_rect().intersects(enclosing_int_rect(absolute_rect())))
  30. return;
  31. PaintableBox::paint(context, phase);
  32. if (phase == PaintPhase::Foreground) {
  33. if (layout_box().renders_as_alt_text()) {
  34. auto& image_element = verify_cast<HTML::HTMLImageElement>(*dom_node());
  35. context.painter().set_font(Gfx::FontDatabase::default_font());
  36. Gfx::StylePainter::paint_frame(context.painter(), enclosing_int_rect(absolute_rect()), context.palette(), Gfx::FrameShape::Container, Gfx::FrameShadow::Sunken, 2);
  37. auto alt = image_element.alt();
  38. if (alt.is_empty())
  39. alt = image_element.src();
  40. context.painter().draw_text(enclosing_int_rect(absolute_rect()), alt, Gfx::TextAlignment::Center, computed_values().color(), Gfx::TextElision::Right);
  41. } else if (auto bitmap = layout_box().image_loader().bitmap(layout_box().image_loader().current_frame_index())) {
  42. auto image_rect = absolute_rect().to_rounded<int>();
  43. ScopedCornerRadiusClip corner_clip { context.painter(), image_rect, normalized_border_radii_data(ShrinkRadiiForBorders::Yes) };
  44. context.painter().draw_scaled_bitmap(image_rect, *bitmap, bitmap->rect(), 1.0f, to_gfx_scaling_mode(computed_values().image_rendering()));
  45. }
  46. }
  47. }
  48. }