math/algorithm Fit image to screen retain aspect ratio
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Fitting an image to a screen while retaining its aspect ratio requires calculating a single scale factor that makes the image as large as possible without exceeding either the screen width or height. The algorithm computes two candidate scale factors (one for width, one for height) and picks the smaller one. This is known as "contain" or "fit" mode. The opposite — filling the screen and potentially cropping — picks the larger scale factor ("cover" mode). Both modes are used everywhere: CSS object-fit, image viewers, game rendering, and responsive design.
The Core Algorithm
Given an image of size (imgW, imgH) and a container of size (containerW, containerH):
The "contain" scale ensures both dimensions fit within the container. The "cover" scale ensures no empty space, but the image may extend beyond the container.
Python Implementation
Centering the Scaled Image
After scaling, center the image in the container by calculating the offset:
The offsets create equal-sized letterbox bars (horizontal) or pillarbox bars (vertical).
JavaScript / Canvas Implementation
CSS object-fit
CSS handles this natively with the object-fit property:
object-fit: contain is exactly the min(scaleX, scaleY) algorithm. object-fit: cover uses max(scaleX, scaleY).
Swift / iOS Implementation
Never Scale Up (Optional Constraint)
Sometimes you want to fit the image but never scale it larger than its original size:
Adding 1.0 as a third candidate for min() caps the scale factor at 100%.
Common Pitfalls
- Dividing integers and getting zero: In languages with integer division (C, Java, Go),
containerW / imgWtruncates to zero if the container is smaller than the image. Cast to float first:(float)containerW / imgW. - Not rounding the final dimensions: Floating-point multiplication can produce values like
799.9999. Without rounding, the image may be 1 pixel too small, leaving a visible gap. Always round to the nearest integer. - Forgetting to clip in cover mode: Cover mode produces dimensions larger than the container. Without clipping (
overflow: hiddenin CSS,clipsToBounds = truein UIKit), the image overflows its container visually. - Confusing contain and cover: "Contain" fits the entire image (may have bars). "Cover" fills the entire container (may crop). Mixing them up results in either unexpected cropping or unexpected letterboxing.
- Ignoring device pixel ratio for retina displays: On high-DPI screens, the physical pixel count is 2x or 3x the logical size. Scale calculations should use logical dimensions for layout but may need physical dimensions for selecting the appropriate image resolution.
Summary
- Contain (fit):
scale = min(containerW/imgW, containerH/imgH)— image fits entirely inside container - Cover (fill):
scale = max(containerW/imgW, containerH/imgH)— image fills container, may crop - Center the scaled image with
offset = (container - scaled) / 2 - CSS
object-fit: containandobject-fit: coverimplement these algorithms natively - iOS
UIImageView.contentModeuses.scaleAspectFit(contain) and.scaleAspectFill(cover) - Add
min(scale, 1.0)to prevent upscaling small images beyond their native resolution
Related reading
- Mathematica fast 2D binning algorithm
- mathematical model to build a ranking/ scoring system
- Matrix determinant algorithm C
- matrix multiplication algorithm time complexity
- Mathematically producing sphere-shaped hexagonal grid
- Matrix multiplication Small difference in matrix size, large difference in timings
- Max-Heapify A Binary Tree
- max-weight k-clique in a complete k-partite graph

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.