skip to content

In SwiftUI, how do you make recipe photos fill square grid thumbnails without stretching or spilling, and why is clipped() needed?

level: juniorimportance: should knowfreq 60%

answer

  1. stretch, fit or fill
  2. resizable scales each axis alone
  3. fill overflows the frame
  4. a frame is only for layout
  5. clear square with an overlay

basics

~10 s

Chain resizable() and scaledToFill() on the Image, give it a square frame, then clipped(). resizable() alone stretches each axis, fill keeps the aspect ratio but overflows the frame, and clipped() hides the overflow.

solid answer

~40 s

`resizable()` lets an `Image` take the size it is offered, but on its own it scales each axis independently, so a landscape photo forced into a square is squashed. `aspectRatio(contentMode:)`, or its shorthands `scaledToFit()` and `scaledToFill()`, keeps the original proportions: `.fit` shows the whole photo with empty bands, `.fill` covers the square and overflows on the long axis. A frame is used only for layout, so the overflow still draws over neighbouring cells until `clipped()` cuts drawing at the frame's edge. In a grid I size the cell with `Color.clear.aspectRatio(1, contentMode: .fit)`, put the filled photo in an `overlay` so the photo's proportions never decide the cell's shape, clip it, and add `contentShape(Rectangle())` when the cell is tappable.

code

swift · 29 lines
swift
import SwiftUI

struct RecipeThumbnail: View {
    let photo: Image

    var body: some View {
        Color.clear
            .aspectRatio(1, contentMode: .fit)
            .overlay {
                photo
                    .resizable()
                    .scaledToFill()
            }
            .clipped()
            .contentShape(Rectangle())
    }
}

struct RecipeGridView: View {
    let photos: [String]

    var body: some View {
        LazyVGrid(columns: [GridItem(.adaptive(minimum: 110), spacing: 8)], spacing: 8) {
            ForEach(photos, id: \.self) { name in
                RecipeThumbnail(photo: Image(name))
            }
        }
    }
}

go deeper

for a junior

Recall the chain resizable(), scaledToFill(), frame, clipped() and say what each step prevents: no scaling, distortion, wrong size, overflow.

for a middle

Explain fit versus fill in terms of proportions and coverage, why a frame does not clip, and why resizable() must precede view modifiers.

for a senior

Show the overlay-on-a-clear-square cell, the explicit content shape for taps, and interpolation choices for small or pixel-art sources.

for a principal

Turn the cell into a shared component so every grid and banner in the app crops photos the same way and design changes land in one place.

## Why a raw photo misbehaves in a grid A recipe app shows server photos of every shape: landscape shots of a tray bake, portrait shots of a layered cake. The grid wants identical squares. SwiftUI gives you three separate tools, and each one fixes only part of the problem: - **`resizable(capInsets:resizingMode:)`**, a method on `Image`, allows the picture to be drawn at a size other than its natural one. - **`aspectRatio(_:contentMode:)`**, with the shorthands `scaledToFit()` and `scaledToFill()`, keeps a ratio while the view scales. - **`clipped(antialiased:)`** stops drawing at the view's bounding frame. ## Step one: resizable() and its trap Without `resizable()`, an `Image` keeps its natural size whatever frame you give it. With it, the image takes the size offered. Apple's article on fitting images notes that, by itself, `resizable()` scales each axis independently: a 4:3 landscape photo placed in a 120 × 120 frame is squeezed horizontally and looks distorted. Because `resizable()` returns an `Image`, it must come before any view modifier. `Image("dish").frame(width: 120, height: 120).resizable()` does not compile, since `frame` returns `some View`, which has no `resizable` member. ## Step two: fit versus fill | Content mode | Shorthand | Result in a square | What you lose | |---|---|---|---| | none (stretch) | `resizable()` only | photo fills the square, distorted | correct proportions | | `.fit` | `scaledToFit()` | whole photo visible, bands on two sides | full coverage of the cell | | `.fill` | `scaledToFill()` | square fully covered, long edge overflows | the photo's edges | Thumbnails almost always use **fill**: a grid of uneven letterboxes looks broken, while losing a little of a photo's edges is normal for a thumbnail. A detail screen that must show the whole dish uses **fit**. ## Step three: clipping the overflow Apple's documentation for `clipped(antialiased:)` says a view's bounding frame is used only for layout, so content that extends beyond it is still visible. A filled 4:3 photo in a 120-point square is 160 points wide; without clipping, 20 points on each side are drawn over the neighbouring cells. `clipped()` cuts the drawing at the frame; `clipShape` does the same with a shape, such as rounded corners. The `antialiased` parameter defaults to `false`. The documentation describes clipping only in terms of what is drawn. When the cell is a button or has a tap gesture, set the hit area explicitly with `contentShape(Rectangle())` so taps match the square you see. ## A grid cell that holds its shape In a lazy grid with adaptive columns, the column decides a cell's width but nothing decides its height. A filled photo given only a width can take its height from its own proportions, so portrait photos make tall cells. A sturdy cell keeps the photo out of the sizing decision: 1. Start from `Color.clear` and give it `aspectRatio(1, contentMode: .fit)`, which makes a square as wide as the column. 2. Put `image.resizable().scaledToFill()` in an `overlay`; an overlay is sized to the view it decorates and never changes that view's size. 3. Apply `clipped()` (or a clip shape) to the square. 4. Add `contentShape(Rectangle())` if the cell responds to taps. The same pattern works for a hero banner: `Color.clear.frame(height: 240).overlay { photo }.clipped()`. ## Quality: interpolation and tiling - Scaling needs **interpolation**. `interpolation(_:)` takes `.none`, `.low`, `.medium` or `.high` and is a hint to the renderer: `.none` keeps hard pixel edges on pixel-art badges, `.high` favours quality when downscaling. - `resizable(resizingMode: .tile)` repeats a small image to fill the frame instead of scaling it, for patterned backgrounds. - `capInsets` keeps the corners of a stretchable image, such as a speech-bubble background, from distorting. ## Common mistakes - Using `scaledToFit()` for thumbnails and getting uneven bands around each photo. - Applying `clipped()` before the `frame`, so it clips to the image's own larger size and the overflow remains. - Writing `scaledToFill()` before `resizable()`, which does not compile, because `scaledToFill()` returns `some View` and `resizable()` is an `Image` method. - Forgetting that the same cell must also look right while the photo is still loading. ## What interviewers listen for They want the three steps named in order with the reason for each: resizable to allow scaling, fill to keep proportions while covering, clipped because a frame does not clip. Mentioning the overlay pattern and the hit area shows you have fought a real grid.

  • Why does Image("dish").frame(width: 120, height: 120).resizable() fail to compile?
    `resizable(capInsets:resizingMode:)` is a method on `Image` that returns an `Image`. `frame(width:height:)` is a view modifier that returns `some View`, which has no `resizable` member. Image-specific methods such as `resizable()`, `renderingMode(_:)` and `interpolation(_:)` therefore come first, before any view modifier.
  • When would you choose scaledToFit() over scaledToFill() for a recipe photo?
    On a detail or zoom screen where the whole dish must be visible, or for a photo whose edges carry meaning, such as a step-by-step collage. `scaledToFit()` keeps everything visible and accepts empty bands; pair it with a background colour so the bands look intentional.
  • How do you keep a 32 × 32 pixel-art badge crisp when it is scaled up?
    Call `interpolation(.none)` on the `Image` along with `resizable()`. Interpolation is how the renderer approximates pixels at a new size; `.none` repeats source pixels instead of smoothing them, so edges stay hard, while `.medium` or `.high` smooth a small source when enlarged.

Fit is a framer adding a mat so the whole print shows; fill is the framer trimming the print so it covers the frame edge to edge. clipped() is the trimming itself: without it, the print hangs over the frame onto the wall.

  • resizable() on its own keeps the photo's aspect ratio.
  • scaledToFill() crops the photo to the frame without anything else.
  • A frame clips whatever its content draws outside it.
  • scaledToFit() always covers the whole cell.
  • resizable() can be called after frame(width:height:).