Expedia Apr 15, 2021

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

Critical Insight

A ZStack with a transparent Rectangle, strategic layoutPriority, and .clipped() solves SwiftUI's image aspect ratio problem where native modifiers fail.

The final solution is surprisingly elegant once you see it, but the journey reveals why SwiftUI's image handling is more complex than it appears.

About This Article

Problem

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.

Solution

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.

Impact

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.

Recent from Expedia

Related Articles