ambient_animation_resizer.cc 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright 2022 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "ash/ambient/ui/ambient_animation_resizer.h"
  5. #include "base/check.h"
  6. #include "base/logging.h"
  7. #include "base/numerics/safe_conversions.h"
  8. #include "ui/gfx/geometry/rect.h"
  9. #include "ui/gfx/geometry/size.h"
  10. #include "ui/lottie/animation.h"
  11. #include "ui/views/controls/animated_image_view.h"
  12. namespace ash {
  13. // static
  14. void AmbientAnimationResizer::Resize(
  15. views::AnimatedImageView& animated_image_view,
  16. int padding_for_jitter) {
  17. DCHECK(animated_image_view.animated_image());
  18. DCHECK_GE(padding_for_jitter, 0);
  19. gfx::Size animation_size =
  20. animated_image_view.animated_image()->GetOriginalSize();
  21. DCHECK(!animation_size.IsEmpty());
  22. gfx::Rect destination_bounds = animated_image_view.GetContentsBounds();
  23. destination_bounds.Outset(padding_for_jitter);
  24. DCHECK(!destination_bounds.IsEmpty());
  25. gfx::Size animation_resized;
  26. float width_scale_factor =
  27. static_cast<float>(destination_bounds.width()) / animation_size.width();
  28. animation_resized.set_width(destination_bounds.width());
  29. // TODO(esum): Add metrics for the number of times the new scaled height
  30. // is less than the destination height. UX did not intend for this to
  31. // happen, so it's worth recording.
  32. animation_resized.set_height(
  33. base::ClampRound(animation_size.height() * width_scale_factor));
  34. animated_image_view.SetVerticalAlignment(
  35. views::ImageViewBase::Alignment::kCenter);
  36. animated_image_view.SetHorizontalAlignment(
  37. views::ImageViewBase::Alignment::kCenter);
  38. // The animation's new scaled size has been computed above.
  39. // AnimatedImageView::SetImageSize() takes care of both a) applying the
  40. // scaled size and b) cropping by translating the canvas before painting such
  41. // that the rescaled animation's origin resides outside the boundaries of the
  42. // view. The portions of the rescaled animation that reside outside of the
  43. // view's boundaries ultimately get cropped.
  44. animated_image_view.SetImageSize(animation_resized);
  45. }
  46. } // namespace ash