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.
Designing a flexible component for handling images in SDL-based applications