Last active
November 28, 2024 19:53
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.