Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save karigrooms/fdf435274f4403abd57b1ed533dcea53 to your computer and use it in GitHub Desktop.
Save karigrooms/fdf435274f4403abd57b1ed533dcea53 to your computer and use it in GitHub Desktop.
ViewModifier for resizing images in SwiftUI. Resize an image to any size (square, circle, rectangle) while maintaining its aspect ratio.
import SwiftUI
/// Common aspect ratios
public enum AspectRatio: CGFloat {
case square = 1
case threeToFour = 0.75
case fourToThree = 1.75
}
/// Fit an image to a certain aspect ratio while maintaining its aspect ratio
public struct FitToAspectRatio: ViewModifier {
private let aspectRatio: CGFloat
public init(_ aspectRatio: CGFloat) {
self.aspectRatio = aspectRatio
}
public init(_ aspectRatio: AspectRatio) {
self.aspectRatio = aspectRatio.rawValue
}
public func body(content: Content) -> some View {
ZStack {
Rectangle()
.fill(Color(.clear))
.aspectRatio(aspectRatio, contentMode: .fit)
content
.scaledToFill()
.layoutPriority(-1)
}
.clipped()
}
}
// Image extension that composes with the `.resizable()` modifier
public extension Image {
func fitToAspectRatio(_ aspectRatio: CGFloat) -> some View {
self.resizable().modifier(FitToAspectRatio(aspectRatio))
}
func fitToAspectRatio(_ aspectRatio: AspectRatio) -> some View {
self.resizable().modifier(FitToAspectRatio(aspectRatio))
}
}
@kris-randen
Copy link

I can’t stress the importance of solving this problem enough when you have images and thumbnails all over the place. Resizing really sucks even now in SwiftUI and it shouldn’t be this complex. Whatever this article does to solve it should ideally become part of SwiftUI's default. Seriously!!
I’m yet to meet someone who says they don't want to have aspect ratio maintained while resizing images and therefore this must be the default and not the crap that SwiftUI currently offers. It’s pathetic! I This is absolutely critical and will save so much time. Please see if you can suggest it as a language / framework feature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment