Building a Versatile Image Class

Implementing Cover Scaling Mode

How can we implement a ScalingMode::Cover option similar to CSS's object-fit: cover?

Abstract art representing computer programming

To implement a ScalingMode::Cover option similar to CSS's object-fit: cover, we need to modify our Image class to include this new scaling mode.

The Cover mode will scale the image to cover the entire destination rectangle while maintaining its aspect ratio, potentially cropping parts of the image that don't fit.

Here's how we can implement this. First, let's update our ScalingMode enum to include the Cover option:

enum class ScalingMode { None, Fill, Contain, Cover };

Next, we'll modify our MatchAspectRatio() function to handle the Cover mode:

SDL_Rect Image::MatchAspectRatio(
  const SDL_Rect& Source,
  const SDL_Rect& Target) const {
  float TargetRatio{ Target.w
    / static_cast<float>(Target.h) };
  float SourceRatio{ Source.w
    / static_cast<float>(Source.h) };

  SDL_Rect ReturnValue = Source;

  if (mScalingMode == ScalingMode::Contain) {
    if (SourceRatio < TargetRatio) {
      ReturnValue.h = static_cast<int>(
        Source.w / TargetRatio);
    } else {
      ReturnValue.w = static_cast<int>(
        Source.h * TargetRatio);
    }
  } else if (mScalingMode
    == ScalingMode::Cover) {
    if (SourceRatio > TargetRatio) {
      int NewWidth = static_cast<int>(
        Source.h * TargetRatio);
      ReturnValue.w = NewWidth;
    } else {
      int NewHeight = static_cast<int>(
        Source.w / TargetRatio);
      ReturnValue.h = NewHeight;
    }
    ReturnValue.x =
      (Target.w - ReturnValue.w) / 2;
    ReturnValue.y =
      (Target.h - ReturnValue.h) / 2;
  }

  return ReturnValue;
}

With these changes, our Image class now supports a Cover scaling mode that behaves similarly to CSS's object-fit: cover.

The image will be scaled to cover the entire destination rectangle while maintaining its aspect ratio, potentially cropping parts of the image that don't fit.

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 51 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved