Resizing Images In SwiftUI
Article Summary
Kari Grooms from Expedia Group's Vrbo team cracked one of SwiftUI's most frustrating puzzles: resizing images without distortion. What should be simple turns into a 10-step journey through modifier hell.
When building Vrbo's iOS 14 Widget and property cards, the team hit a wall with SwiftUI's image resizing. Standard modifiers like .resizable() and .aspectRatio() either skewed images or failed to constrain them properly. After exhaustive experimentation, they developed a reusable solution using an unexpected trick.
Key Takeaways
- Standard SwiftUI modifiers (.resizable, .aspectRatio) consistently skew or fail to constrain images
- Solution uses hidden Rectangle with .layoutPriority(-1) to dictate image dimensions
- Custom ViewModifier supports square, 4:3, 3:4, and custom aspect ratios
- Technique now powers property images across every Vrbo iOS screen
A ZStack with a transparent Rectangle, strategic layoutPriority, and .clipped() solves SwiftUI's image aspect ratio problem where native modifiers fail.
About This Article
Kari Grooms' team at Vrbo ran into a problem with SwiftUI's built-in image resizing. The native modifiers were distorting images across different screen sizes, so they needed a better approach for the property photos that appear throughout the app at various dimensions.
They built a custom ViewModifier that layers a transparent Rectangle with .layoutPriority(-1), .scaleToFill(), and .clipped(). This keeps aspect ratios intact and works with preset options like square, 4:3, and 3:4, plus custom ratios too.
The fitToAspectRatio() modifier fixed image distortion in Vrbo's iOS 14 Widget and property cards. Images now render consistently at the right aspect ratio no matter what size container they're in, without needing separate fixes for each screen.